当Spring Security对用户进行身份验证时,如何在会话中管理自定义用户对象? [英] How to manage a custom user object in session when Spring Security authenticates user?

查看:178
本文介绍了当Spring Security对用户进行身份验证时,如何在会话中管理自定义用户对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring Security 对用户进行身份验证时,它会创建一个UserDetail对象,并且可以查找当前对象Web应用程序中的UserId。但是,假设我想保留一个带有首选项和其他详细信息的自定义用户对象以及UserDetails或替换UserDetails。

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.

那么,当Spring Security成功验证
时,如何将自定义用户对象添加到会话?以及如何在Spring Security注销登录用户时从会话中删除自定义用户对象。

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?

推荐答案

执行此操作的最佳方法IMO是让您的一个服务(可能是UserService)实现UserDetailsS​​ervice并在春季指定您希望使用自己的用户详细信息服务的安全XML。

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.

UserDetailsS​​ervice需要做的是实现loadByUsername(String username)方法。此方法需要返回一个实现UserDetails的类。这可以是您自己的自定义对象存储您喜欢的任何内容。这样做的好处是,您可以通过spring security taglib从JSP访问对象的属性,并且它也始终可以从Spring Security Text中的SecurityContextHolder单例(线程安全)中获得。

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.

这是以下文档的链接: spring security manual,chapter 8
这是一篇关于实现的博客文章用于密码加密的自定义用户详细信息服务:示例用法

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

希望这会有所帮助

编辑:忘记提及在注销时将从安全上下文和会话中删除该对象。这是最有用的,它完全由春季安全管理。

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.

这篇关于当Spring Security对用户进行身份验证时,如何在会话中管理自定义用户对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆