3

Is there a "getCurrentUser" method in Spring to access the user that is currently part of a request - even if that user's name is not being passed around as part of a web request?

apfel
  • 217
  • 1
  • 8
  • 11

1 Answers1

10

Since you have tagged your question with spring-security I assume your question is in same context. With spring-security you can retrieve current user as :

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDetails userDetails = null;
if (principal instanceof UserDetails) {
  userDetails = (UserDetails) principal;
}
String userName = userDetails.getUsername();
Gopi
  • 10,073
  • 4
  • 31
  • 45
  • Also Spring Security exposes its authentication data via `HttpServletRequest.getPrincipal()`. – axtavt Aug 19 '10 at 16:21
  • 1
    this does not work for me getAuthentication() returns null, even though user is logged in http://stackoverflow.com/q/7811200/106261 – NimChimpsky Oct 18 '11 at 17:58