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

后端 未结 2 1886
花落未央
花落未央 2021-02-18 20:32

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 ob

相关标签:
2条回答
  • 2021-02-18 21:05

    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.

    0 讨论(0)
  • 2021-02-18 21:23

    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.getParameter("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 removed when the user is removed (like at log out).  

    0 讨论(0)
提交回复
热议问题