When Spring Security authenticates user, it creates a UserDetail object and it is available for finding current UserId in web-app. But let's say I want to keep a custom user object with preferences and other details along with UserDetails or Replacing UserDetails.
So, how to add Custom User object to session when Spring Security authenticates successfully? And how to remove custom user object from session when Spring Security logs out logged-in user.
Or is there any appropriate way to do this?
SessionManagementFilter in Spring Security web. session. SessionManagementFilter. In XML configuration it's represented by a tag called <session-management />.
Simply put, Spring Security hold the principal information of each authenticated user in a ThreadLocal – represented as an Authentication object. In order to construct and set this Authentication object – we need to use the same approach Spring Security typically uses to build the object on a standard authentication.
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
The best way to do this IMO is to have one of your services (probably UserService) implement UserDetailsService and specify in the spring security XML that you wish to use your own user details service.
What the UserDetailsService will need to do is implement a loadByUsername(String username) method. This method will need to return a class that implements UserDetails. This can be your own custom object storing whatever you like. The advantage of this is that you can access the object's properties from a JSP via spring security taglib and it is also always available from the SecurityContextHolder singleton (thread safe) in spring security.
Here is a link to the docs for this: spring security manual, chapter 8 Here is a blog post talking about implementing a custom user details service for password encryption: example usage
Hope this helps
Edit: Forgot to mention that the object will be removed from the security context and session on logout. That is what is most useful about it, it is fully managed by spring security.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With