有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我可以使用spring security在cookies中存储完整的用户信息吗?记住我

我想将其他用户信息存储在cookie中,比如带有用户名和密码的userId。当我使用spring security记住我的功能时,我可以从cookies中获取用户名

春天的安全。xml我使用的是定制的userDetailService,我已经像这样实现了它

 <http>
 ......   
 <logout invalidate-session="true" 
        logout-success-url="/" 
        logout-url="/logout.htm"/>
 <remember-me user-service-ref="myUserDetailsService" key="89dqj219dn910lsAc12" token-validity-seconds="864000"/>
</http>

<authentication-manager>
        <authentication-provider user-service-ref="myUserDetailsService">
                <password-encoder ref="myEnocdePassword" >
                    <salt-source user-property="username"/>
                </password-encoder>
        </authentication-provider>
</authentication-manager>   
<beans:bean id="myEnocdePassword" class="com.mycom.myproject.utility.MyEnocdePassword" />

在MyUserDetailService中。我有类似java的代码

  @Override
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException {

    try {

    boolean enabled = true;
    boolean accountNonExpired = true;
    boolean credentialsNonExpired = true;
    boolean accountNonLocked = true;

    com.mycom.myproject.db.mybatis.model.User domainUser = userService.getUserByName(username);




    return  new User(
            domainUser.getUsername(), 
            domainUser.getPassword(),
            enabled,
            accountNonExpired,
            credentialsNonExpired,
            accountNonLocked,
            getAuthorities(domainUser.getRoleId);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

在我的控制器类中,我可以使用

   String name = SecurityContextHolder.getContext().getAuthentication()
            .getName();

但是我想在cookie中存储其他用户详细信息,比如userId。我怎么能做到?我是否需要通过userDao(name)获取用户信息,然后手动将用户信息存储在cookie中


共 (2) 个答案

  1. # 1 楼答案

    在这种情况下,你不需要对饼干做任何事情

    只要用户登录(无论他如何登录-使用登录表单或“记住我”),您就可以从SecurityContext访问该用户的UserDetails,Spring Security会处理它

    因此,您只需将所需信息放入UserDetailsService.loadUserByUsername()中的UserDetails(如果需要,使用您自己的UserDetails子类),并通过SecurityContext访问它:

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        Object principal = auth.getPrincipal();  
        if (principal instanceof UserDetails) {
            UserDetails user = (UserDetails) principal;
            ... // User is logged in, now you can access its details
        }
    }
    

    换句话说,当Spring Security接收到一个没有活动会话但带有RememberMe cookie的请求时,它使用cookie中的用户标识来加载UserDetails,并将它们放入SecurityContext(以及新创建的会话)。稍后,您可以从SecurityContext访问这些详细信息

  2. # 2 楼答案

    通常已经有饼干了! 您可以在会话中存储这些值

    如果希望长时间存储这些值,可以使用会话钝化