How to get the current logged in user object from spring security?

spring boot security get current user
spring security get user id
spring security get all logged in users
spring security principal
securitycontextholder.getcontext().getauthentication() returns null spring boot
spring security principal is null
spring get user object
spring security get user firstname

I am using Spring security version 3.1.4.RELEASE. How can I access the current logged in user object?

SecurityContextHolder.getContext().getAuthentication().getPrinciple()

returns user name, not user object. So how can I use the returned Username and get the UserDetails object?

I have tried the following code:

public UserDetails getLoggedInUser(){

    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken))
    {
        if(auth.getDetails() !=null)
            System.out.println(auth.getDetails().getClass());
        if( auth.getDetails() instanceof UserDetails)
        {
            System.out.println("UserDetails");
        }
        else
        {
            System.out.println("!UserDetails");
        }
    }
    return null;
}

Following is the result:

[2015-08-17 19:44:46.738] INFO  http-bio-8443-exec-423   System.out    class org.springframework.security.web.authentication.WebAuthenticationDetails 
[2015-08-17 19:44:46.738] INFO  http-bio-8443-exec-423   System.out    !UserDetails

AuthenticationFilter class as follows:

public class CustomUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
    public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";
    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    private boolean postOnly = true;

    public CustomUsernamePasswordAuthenticationFilter() {
        super("/j_spring_security_check");
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String username = obtainUsername(request);
        String password = obtainPassword(request);
        if (username == null) {
            username = "";
        }
        if (password == null) {
            password = "";
        }
        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);
        if(this.getAuthenticationManager()==null){
            logger.info("Authentication manager is null.");
        } else {
            logger.info("Authentication manager was "+this.getAuthenticationManager().getClass().getName()); 
        }
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(passwordParameter);
    }

    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(usernameParameter);
    }

    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setUsernameParameter(String usernameParameter) {
        this.usernameParameter = usernameParameter;
    }

    public void setPasswordParameter(String passwordParameter) {
        this.passwordParameter = passwordParameter;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getUsernameParameter() {
        return usernameParameter;
    }

    public final String getPasswordParameter() {
        return passwordParameter;
    }
}

AuthenticationProvider as follows:

@Component
public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    private MyUserDetailsService userDetailsService;

    public MyUserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(MyUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails arg0,
            UsernamePasswordAuthenticationToken arg1)
            throws AuthenticationException {

    }

    @Override
    protected UserDetails retrieveUser(String arg0,
            UsernamePasswordAuthenticationToken arg1)
            throws AuthenticationException {
        return userDetailsService.loadUserByUsername(arg0);
    }
}

UserDetails class as follows:

    public class MyUserDetailsService implements UserDetailsService {       
    private final Map<String, UserDetails> usersList;

    public MyUserDetailsService() {
        Collection<GrantedAuthority> authorityList;
        final SimpleGrantedAuthority supervisorAuthority = new SimpleGrantedAuthority("supervisor");
        final SimpleGrantedAuthority userAuthority = new SimpleGrantedAuthority("user");
        usersList = new TreeMap<String, UserDetails>();

        authorityList = new ArrayList<GrantedAuthority>();
        authorityList.add(supervisorAuthority);
        authorityList.add(userAuthority);
        usersList.put("admin", new User("admin", "admin", authorityList));

        authorityList = new ArrayList<GrantedAuthority>();
        authorityList.add(userAuthority);
        usersList.put("peter", new User("peter", "password123", authorityList));

        //probably don't use this in production
        for(Map.Entry<String, UserDetails> user : usersList.entrySet()){
            logger.info(user.getValue().toString());
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException {
        UserDetails ud = usersList.get(username);
        if (ud != null) {
            logger.info("loadUserByUsername: found match, returning "
                    + ud.getUsername() + ":" + ud.getPassword() + ":"
                    + ud.getAuthorities().toString());
            return new User(ud.getUsername(), ud.getPassword(),
                    ud.getAuthorities());
        }

        logger.info("loadUserByUsername: did not find match, throwing UsernameNotFoundException");
        throw new UsernameNotFoundException(username);
    }
}
SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Returns the current user object. This can be User, UserDetails or your custom user object. You will need to cast the return object to UserDetails or your own user object if it is a custom one.

OR you can inject Authentication or Principal directly in to your controllers. Principle is your UserDetails/custom user object.

Note: UserDetails is an interface

How to get the current logged in user object from spring security , How to get the currently logged in user with Spring Security. Because of this, the Spring Security principal can only be retrieved as an Object and needs to be cast System.out.println( "User has authorities: " + userDetails. How to Get the Current Logged-In Username in Spring Security Here is the code to get the SecurityContext in Spring Security and obtain the name of the currently logged-in user: Object principal =

you can use it like

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}

it is in spring security reference http://docs.spring.io/spring-security/site/docs/4.0.2.RELEASE/reference/htmlsingle/#obtaining-information-about-the-current-user

Retrieve User Information in Spring Security, Get current logged in username in Spring Security. Download Source Code. Download it – Spring-Security-Get-Logged-In-Username.zip (9 KB) I m trying your first example , i am unable to get the authentication object . In this short article, I show you how to get current logged-in username in JSP using Spring Security. Spring Security has its own spring-security-taglibs library, which provides basic support for accessing security information and applying security constraints in JSPs.

You just went one step foo far. SecurityContextHolder.getContext().getAuthentication() returns an Authentication object. You should know how you authenticated the user, and what can the the concrete class implementing Authentication. Assuming it is a subclass of AbstractAuthenticationToken (all Spring provided implementation are), and getDetails() returns a UserDetails, you can just use:

AbstractAuthenticationToken auth = (AbstractAuthenticationToken)
    SecurityContextHolder.getContext().getAuthentication();
UserDetails details = (UserDetails) auth.getDetails();

Get current logged in username in Spring Security, Spring Security - Get Current Logged-In User Details Because of this, the Spring Security principal can only be retrieved as an Object and needs to be cast to  In this article, we will show you three ways to get the current logged in username in Spring Security. 1. SecurityContextHolder + Authentication.getName() import org.springframework.security.core.Authentication;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.

You can simply inject the Authentication Interface to your Controller and get the username of the logged in user, like below:

@Controller
public class SomeController {

    @GetMapping(value = "/username")
    @ResponseBody
    public String currentUserName(Authentication authentication) {

        if (authentication != null) {
            return authentication.getName();

        } else {
            return "";
        }
    }
}

Spring Security - Get Current Logged-In User Details, How to retrieve and log the current user with Auth0 / Spring Boot / Spring Security​? Spring Boot API secured with auth0-spring-security-api 1.1.0 (and I'm (​name or email) through this AuthenticationJsonWebToken object? This article showed how to get the user information in a Spring application, starting with the common static access mechanism, followed by several better ways to inject the principal. The implementation of these examples can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.

How to retrieve and log the current user with Auth0 / Spring Boot , You can get the current Principal object from Authentication object and get the username and other details like for example check if the user  Before jumping on to the advanced details on spring security, lets learn about how to get the currently logged in user details. This example illustrates how to get the user details in the controller using the spring security API. Also this examples redirect to the different landing pages depends on the user names.

Spring Security. Get Authenticated Principal Details., User user = (User) SecurityContextHolder.getContext().getAuthentication().​getPrincipal(); You can invoke the getter for id on user object. 2.2k views  I have other apps who can access this url if they have the roles set up.. so another app has this role set up, and they access this url.. in my controller im trying to get the user name.. thats where im stuck as i only get "annonymous user" – user1555190 Sep 17 '12 at 7:36

How to Get current logged in userId in Spring Security, How to get the current user in a Spring Security reactive (WebFlux) and non-​reactive need to access the currently logged in user programmatically. When someone logs in, Spring Security creates an Authentication object. If you already know for sure that the user is logged in (in your example if /index.html is protected): UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); To first check if the user is logged in, check that the current Authentication is not a AnonymousAuthenticationToken.

Comments
  • How do you authenticate your users? What is the AuthenticationProvider, and what is the Filter?
  • Ok, you a custom AuthenticationFilter not far from a UsernamePasswordAuthenticationFilter. It is common to use a DaoAuthenticationProvider with that. Did you configure setForcePrincipalAsString(True) (or set forcePrincipalAsString to true) anywhere?
  • @SergeBallesta No I didn't use those methods
  • With the shown code and a default (or common) configuration, SecurityContextHolder.getContext().getAuthentication().getPrincipal() should return the User object provided by MyUserDetailsService. You should try to use a debugger to follow a full authentication request (after downloading sources for SpringSecurity)
  • Or do you have anything (a filter or ?) that would use the authentication object to set the request Principal to the user name ?
  • Also a mkyong how-to w/ slightly more details.
  • How to get the user's id?
  • There is a username (String) field in the User/UserDetails class/interface, if your user's id is the username.
  • I am getting java.lang.ClassCastException. please help me
  • I am getting username but not user Object.
  • I think you have to check the next paragraph after the mentioned above docs.spring.io/spring-security/site/docs/4.0.2.RELEASE/… to get user details using UserDetailsService
  • I am getting an instance of WebAuthenticationDetails instead of UserDetails.