zoukankan      html  css  js  c++  java
  • spring security 用JPA进行安全管理中使用自定义的UserDetails时,maximumSessions()无法限制Session数

    这是我自定义的UserDetails,这个user对象会保存到数据库。

    //自定义的User
    @Entity(name = "t_user")
    public class User implements UserDetails, CredentialsContainer {
            @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String username;
        private String password;
        //...其他字段
    }
    

    而ConcurrentSessionControlAuthenticationStrategy#onAuthentication在执行sessionRegistry.getAllSessions方法时会到sessionRegistry的一个Map中去获取当前用户的所有session。Map.get的key是这个Principal,也就是User对象实例,之前我没有重写User的hascode和equals方法,(Map.get方法是根据hashcode获取value的,而未重写hascode,默认使用父类Object的hashcode方法,Object#hashcode相当于返回对象的内存地址),所以取出来的sessions是空集合,系统认为该用户没有在其他地方登录过。

    //ConcurrentSessionControlAuthenticationStrategy#onAuthentication
    public void onAuthentication(Authentication authentication, HttpServletRequest request,
          HttpServletResponse response) {
       List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(authentication.getPrincipal(), false);
       int sessionCount = sessions.size();
       int allowedSessions = getMaximumSessionsForThisUser(authentication);
       if (sessionCount < allowedSessions) {
          // They haven't got too many login sessions running at present
          return;
       }
    }
    

    另外要注意,重写User的hascode和equals只需要判断username字段即可,因为用户密码和id都可能变化,但在这些变化后我们仍认为它是同一个用户。可以参考spring security自带的org.springframework.security.core.userdetails.User的这两个方法

    //org.springframework.security.core.userdetails.User
    public class User implements UserDetails, CredentialsContainer {
    	/**
    	 * Returns {@code true} if the supplied object is a {@code User} instance with the
    	 * same {@code username} value.
    	 * <p>
    	 * In other words, the objects are equal if they have the same username, representing
    	 * the same principal.
    	 */
    	@Override
    	public boolean equals(Object obj) {
    		if (obj instanceof User) {
    			return this.username.equals(((User) obj).username);
    		}
    		return false;
    	}
    
    	/**
    	 * Returns the hashcode of the {@code username}.
    	 */
    	@Override
    	public int hashCode() {
    		return this.username.hashCode();
    	}
    
    }
    
  • 相关阅读:
    [Vue音乐项目] 第六节 歌单列表
    [Vue音乐项目] 第五节 服务器代理跨域
    [Vue音乐项目] 第四节 轮播图
    [Vue音乐项目] 第三节 JSONP跨越
    [Vue音乐项目] 第二节 前提工作
    [Vue音乐项目] 第一节 环境搭建
    HTML网页页脚版权标志
    移动端页面隐藏滚动条
    FDD项目中的总结
    bootstrap模态窗字体模糊
  • 原文地址:https://www.cnblogs.com/gocode/p/14814706.html
Copyright © 2011-2022 走看看