SpringSecurity-11-只允许一个用户登录

SpringSecurity-11-只允许一个用户登录

本次给你介绍只允许用户在一个地方登录,也就是说每个用户只允许有一个Session。他有两种场景

  • 如果同一个用户在第二个地方登录,则将第一个登录下线

  • 如果同一个用户在第二个地方登录,则不允许二次的登录

同一个用户在第二个地方登录,则将第一个登录退出

具体步骤如下:

  1. 重构com.security.learn.config.LearnSrpingSecurity的configure(HttpSecurity http)方法
     @Autowired
    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy;
            
            .and()
                .sessionManagement()
                .invalidSessionStrategy(invalidSessionStrategy)
                .maximumSessions(1) 每个用户在系统中的最大session数
               // .maxSessionsPreventsLogin(true)
                .expiredSessionStrategy(sessionInformationExpiredStrategy)// 当用户达到最大session数后,则调用此处的实现

  • 自定义SessionInformationExpiredStrategy实现类来定制策略
import com.fasterxml.jackson.databind.ObjectMapper;
import com.security.learn.handler.MyAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import java.io.IOException;

public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

    //Jackson JSON数据处理类
    private  static ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        // 1. 获取用户名
        UserDetails userDetails =
                (UserDetails)event.getSessionInformation().getPrincipal();

        AuthenticationException exception =
                new AuthenticationServiceException(
                        String.format("[%s] 用户在另外一台电脑登录,您已被下线", userDetails.getUsername()));

        try {
            // 当用户在另外一台电脑登录后,交给失败处理器回到认证页面
            event.getRequest().setAttribute("toAuthentication" , true);
            myAuthenticationFailureHandler
                    .onAuthenticationFailure(event.getRequest(), event.getResponse(), exception);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}

  • 在com.security.learn.config.Myconfig类中注入SessionInformationExpiredStrategy
    @Bean
    @ConditionalOnMissingBean(SessionInformationExpiredStrategy.class)
    public SessionInformationExpiredStrategy informationExpiredStrategy(){
        return new MySessionInformationExpiredStrategy();
    }


测试:

  1. 谷歌浏览器用户名密码登录

  2. 再使用火狐浏览器用户名密码登录

  3. 回到谷歌浏览器刷新请求,发现回到登录页面,提示被下线

如果同一个用户在第二个地方登录,则不允许二次的登录


如果同一用户在第2个地方登录时,则不允许他二次登录。

实现步骤:

  1. 在 LearnSrpingSecurity添加 maxSessionsPreventsLogin(true) 后不允许二次登录,其实就是添加一个 .maxSessionsPreventsLogin(true)。
                .and()
                .sessionManagement()
                .invalidSessionStrategy(invalidSessionStrategy)
                .maximumSessions(1) 每个用户在系统中的最大session数
                .maxSessionsPreventsLogin(true)
                .expiredSessionStrategy(sessionInformationExpiredStrategy)// 当用户达到最大session数后,则调用此处的实现
                ;

测试:

  1. 谷歌浏览器用户名密码登录

  2. 再使用火狐浏览器用户名密码登录,发现不允许登录

解决同一用户的手机重复登录问题


使用了 admin 用户名登录后,还可以使用这个用户的手机号登录。正常应该是同一个用户,系统中只能用用户名或手机号登录一次。

解决问题:

原因是 SmsCodeAuthenticationFilter继承的类 AbstractAuthenticationProcessingFilter 中,默认使用了 NullAuthenticatedSessionStrategy 实例管理 Session,我们应该指定用户名密码过滤器中所使用的那个 SessionAuthenticationStrategy 实现类 CompositeSessionAuthenticationStrategy 。在com.security.learn.config.SmsCodeSecurityConfig指定即可解决:

@Component
public class SmsCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    @Qualifier("smsCodeUserDetailsService")
    private SmsCodeUserDetailsService smsCodeUserDetailsService;

    @Resource
    private SmsCodeValidateFilter  smsCodeValidateFilter;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //创建手机校验过滤器实例
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        //接收 AuthenticationManager 认证管理器
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //处理成功handler
        //smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        //处理失败handler
        //smsCodeAuthenticationFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
        smsCodeAuthenticationFilter.setRememberMeServices(http.getSharedObject(RememberMeServices.class));
        smsCodeAuthenticationFilter.setSessionAuthenticationStrategy(http.getSharedObject(SessionAuthenticationStrategy.class));
        // 获取验证码提供者
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(smsCodeUserDetailsService);

        //在用户密码过滤器前面加入短信验证码校验过滤器
        http.addFilterBefore(smsCodeValidateFilter, UsernamePasswordAuthenticationFilter.class);
        //在用户密码过滤器后面加入短信验证码认证授权过滤器
        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }
}

退出系统


解决退出不允许再次登录

配置了 .maxSessionsPreventsLogin(true) 开启了前面已登录,不允许再重复登录上面默认情况,如果登录后,然后请求 /logout 退出,再重新登录时,会提示不能重复登录。

源码分析

每次登录请求都会执行 ConcurrentSessionControlAuthenticationStrategy#onAuthentication判断用户在系统是否已经存在 session了, 且判断是否已经超过限制的session数量了,超出则抛异常

原因是退出时,并没有将 SessionRegistryImpl.principals缓存用户信息进行删除

@Override
 public void onAuthentication(Authentication authentication, HttpServletRequest request,
   HttpServletResponse response) {
  int allowedSessions = getMaximumSessionsForThisUser(authentication);
  if (allowedSessions == -1) {
   // We permit unlimited logins
   return;
  }
  // 获取当前用户在系统中的所有 session
  List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(authentication.getPrincipal(), false);
  int sessionCount = sessions.size();
  if (sessionCount < allowedSessions) {
   // 用户session总个数 小于 设置的最大session数 ,则直接通过
   return;
  }
        // 创建session
  if (sessionCount == allowedSessions) {
   HttpSession session = request.getSession(false);
   if (session != null) {
    // Only permit it though if this request is associated with one of the
    // already registered sessions
    for (SessionInformation si : sessions) {
     if (si.getSessionId().equals(session.getId())) {
      return;
     }
    }
   }
  
  }
        // 超出允许的 session 的个数 , maxSessionsPreventsLogin(true)抛出异常不让登录
  allowableSessionsExceeded(sessions, allowedSessions, this.sessionRegistry);
 }


解决方案

  • 在com.security.learn.config.Myconfig中注入SessionRegistry
    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }


  • 添加一个退出处理器com.security.learn.handler.MyLogoutHandler ,将用户信息从缓存中清

@Component
public class MyLogoutHandler implements LogoutHandler {

    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    public void logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Authentication authentication) {
        // 退出之后 ,将对应session从缓存中清除 SessionRegistryImpl.principals
        sessionRegistry.removeSessionInformation(request.getSession().getId());
    }
}

SpringSecurityConfifig 注入 customLogoutHandler

自定义退出处理

在 com.security.learn.config.LearnSrpingSecurity注入MyLogoutHandler

    /**
     * 退出清除缓存
     */
    @Autowired
    private MyLogoutHandler myLogoutHandler;
    @Autowired
    private SessionRegistry sessionRegistry;

                .and().logout()
                .addLogoutHandler(myLogoutHandler)
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login/page")
                .deleteCookies("JSESSIONID")

如果您觉得本文不错,欢迎关注,点赞,收藏支持,您的关注是我坚持的动力!
原创不易,转载请注明出处,感谢支持!如果本文对您有用,欢迎转发分享!

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值