Spring Security - Get Current Logged-In User Details

In this article, we will discuss different ways to retrieve the currently logged-in user details in Spring Security.
Let's see how programmatic access currently authenticated user.

1. Using SecurityContextHolder + Authentication.getName()

The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
    String currentUserName = authentication.getName();
    return currentUserName;
}

2. Using SecurityContextHolder + UserDetails.getUsername()

The API of the Authentication class is very open so that the framework remains as flexible as possible. Because of this, the Spring Security principal can only be retrieved as an Object and needs to be cast to the correct UserDetails instance:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetails = (UserDetails) authentication.getPrincipal();

// getUsername() - Returns the username used to authenticate the user.
System.out.println("User name: " + userDetails.getUsername());

// getAuthorities() - Returns the authorities granted to the user.
System.out.println("User has authorities: " + userDetails.getAuthorities());

3. Get the User in a Controller

In a @Controller annotated bean, there are additional options. The principal can be defined directly as a method argument and it will be correctly resolved by the framework:
@Controller
public class SecurityController {
 
    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Principal principal) {
        return principal.getName();
    }
}
Alternatively, we can also use the authentication token:
@Controller
public class SecurityController {
 
    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Authentication authentication) {
        return authentication.getName();
    }
}

4. How to Get a Current Logged In Username in JSP

5. How to Access User Roles in JSP

6. How to Get Current Logged-In Username in Themeleaf

Comments