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

后端 未结 2 1885
花落未央
花落未央 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: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 m = new HashMap;
          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.

    
       
     
    

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

提交回复
热议问题