How to get user information in Spring

October 8, 2016 - 8:08pm
Submitted by gary

few ways to get the user information:

-User user= (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
this pulls the whole user object.

- Principal userPrincipal = request.getUserPrincipal();
this pulls the user principal, which has access to the username by doing:
userPrincipal.getName();

- User currentUser = request.getSession(false).getAttribute("SPRING_SECURITY_CONTEXT").getAuthentication().getPrincipal();
you may do a few null checks, but this is the long and early way to get the user. Works in the filters too.