1

See link below ..

Spring security access UserDetailsService from deeper layers

Everywhere I read it says UserDetails or principal is automatically stored by Spring in session on successful Authentication. But is it really done ? By Which name then ? Is it possible to get UserDetails from session by session.getAttribute(...) ?

All other methods are ok, but I am confused about this

Community
  • 1
  • 1
Vikash
  • 2,046
  • 3
  • 23
  • 30

1 Answers1

1

Yes, each execution thread has an associated SecurityContext context. You can retrieve the authentication / user details by using SecurityContextHolder like this:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

Here's a good tutorial about this: http://www.baeldung.com/get-user-in-spring-security

Jigish
  • 1,764
  • 1
  • 15
  • 20
  • This is fine. But My question is, Is it saved in session? If yes, then how to get it from session.getAttribute. I think seson.getAttribute is the only way to fetch values in user session. – Vikash Nov 13 '14 at 02:28
  • Are you writing Spring MVC code? If yes, the sample code shows how you can get details about user in the Controller. It would help if you post some sample code that shows what you're trying to do. – Jigish Nov 13 '14 at 03:21
  • I am using SecurityContextHolder.getContext().getAuthentication() But I just want to know is it possible to find userdetails using session.getAttribute() function. Because in my application all other session attributes are accessed using session.getAttribute(). But not the User Details ... . so the only question is is it really holded by session object ? ? – Vikash Nov 14 '14 at 01:58
  • I don't have a definitive answer but it doesn't look like you could retrieve it from HttpSession object. When they say that "UserDetails or principal is automatically stored by Spring in session", they mean that each execution thread has its own UserDetails or principal object. – Jigish Nov 14 '14 at 17:15