views:

475

answers:

2

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?

+2  A: 

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.

Gennadiy
A: 

You definitely need to write your own UserDetailService. In the Principal object there is the user and there is also a Details object in the AuthenticationToken that you can store a Map(String, String) of other login info.

public class RequestFormDeatils extends SpringSecurityFilter {

   protected void doFilterHttp(HttpServletRequest request, ...) {
      SecurityContext sec = SecurityContextHolder.getContent();
      AbstractAuthenticationToken auth = (AbstractAuthenticationToken)sec.getAuthentication();
      Map<String, String> m = new HashMap<String, String>;
      m.put("myCustom1", request.getParamtere("myCustom1"));
      m.put("myCustom2", request.getParameter("myCustom2"));
      auth.setDetails(m);
}

Now anywhere in your code you get use the SecurityContext to propagate this security related info without having to couple it to your UserDetails object, or pass it as arguments. I do this code in a SecurityFilter at the end of the Spring Security Filter chain.

<bean id="requestFormFilter" class="...RequestFormDetails">
   <custom-filter position="LAST" />
</bean>

This info will be reqmoved when the user is removed (like at log out).

Gandalf