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

后端 未结 2 1893
花落未央
花落未央 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.

提交回复
热议问题