Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage a custom user object in session when Spring Security authenticates user?

Tags:

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?

like image 924
Nachiket Avatar asked Dec 08 '09 11:12

Nachiket


People also ask

Which tag is used to manage session in Spring Security?

SessionManagementFilter in Spring Security web. session. SessionManagementFilter. In XML configuration it's represented by a tag called <session-management />.

How do I manually set an authenticated user in Spring Security?

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.

What is SecurityContextHolder getContext () getAuthentication ()?

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.


1 Answers

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.

like image 105
Gennadiy Avatar answered Sep 22 '22 11:09

Gennadiy