How to get the current logged in user object from spring security?
Solution 1:
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
Solution 2:
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
Solution 3:
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();