(八)Spring Security 防止用户重复登录

目录


我们接着上一章(七)Spring Security基于ajax登录,进行开发

本篇介绍如何实现一个用户只允许同时在一个地点登录

  1. 基本配置 踢掉之前的登陆
    protected void configure(HttpSecurity http) throws Exception {
    	http.sessionManagement()
    			.maximumSessions(1).expiredUrl("/login");
    
    maximumSessions配置一个用户的最大session数量,默认不限,这里设1。先在一个浏览器如chrome登录,然后在另一个浏览器如firefox登录,此时同时登录数为2超出参数1,之前chrome的session将会过期,再去chrome发出请求会跳转到过期url。
  2. 防止再次登录
    protected void configure(HttpSecurity http) throws Exception {
    	http.sessionManagement()
    			.maximumSessions(1).maxSessionsPreventsLogin(true);
    
    此时不会踢出之前的登录者,而是先登录者建立了唯一session,在他注销或关闭浏览器之前,不允许异地再次登录。
  3. 上面两种都需配置
    http..logout()
             .logoutSuccessUrl("/home").invalidateHttpSession(true);
    

注意:
Spring Security 是使用org.springframework.security.core.userdetails.User类作为用户登录凭据( Principal )的。该类中重写了equals()和hashCode(),使用username属性作为唯一凭据。
在这里插入图片描述
那么我们实现的UserDetails也应该重写equals()和hashCode()
在这里插入图片描述
在User中重写
在这里插入图片描述
工作原理

在org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy包下的onAuthentication方法(每次用户登录都会触发),会依据用户登录的authentication取出改用户在服务器的所有session,并计算该用户在服务器创建了多少个session,如果session多于设置的数量,会使用排序算法,得到最早的session,并将其设置为过期(删除)

项目地址
Spring Security 防止用户重复登录

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章