Spring-security源码-Filter之ConcurrentSessionFilter(十五)

用于校验session是否过期 过期移除

初始化处:org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer#configure

复制代码
  public void configure(H http) {
        SecurityContextRepository securityContextRepository = http.getSharedObject(SecurityContextRepository.class);
        SessionManagementFilter sessionManagementFilter = new SessionManagementFilter(securityContextRepository,
                getSessionAuthenticationStrategy(http));
        if (this.sessionAuthenticationErrorUrl != null) {
            sessionManagementFilter.setAuthenticationFailureHandler(
                    new SimpleUrlAuthenticationFailureHandler(this.sessionAuthenticationErrorUrl));
        }
        InvalidSessionStrategy strategy = getInvalidSessionStrategy();
        if (strategy != null) {
            sessionManagementFilter.setInvalidSessionStrategy(strategy);
        }
        AuthenticationFailureHandler failureHandler = getSessionAuthenticationFailureHandler();
        if (failureHandler != null) {
            sessionManagementFilter.setAuthenticationFailureHandler(failureHandler);
        }
        AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class);
        if (trustResolver != null) {
            sessionManagementFilter.setTrustResolver(trustResolver);
        }
        sessionManagementFilter = postProcess(sessionManagementFilter);
        http.addFilter(sessionManagementFilter);
        //如果return this.maximumSessions != null;
        if (isConcurrentSessionControlEnabled()) {
            ConcurrentSessionFilter concurrentSessionFilter = createConcurrencyFilter(http);

            concurrentSessionFilter = postProcess(concurrentSessionFilter);
            http.addFilter(concurrentSessionFilter);
        }
    }
复制代码

 

继承WebSecurityConfigurerAdapter 重写

com.liqiang.demo.config.SecurityConfig#configure

复制代码
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and().rememberMe()//记住登录
                .tokenRepository(new InMemoryTokenRepositoryImpl())
                .and()
                .formLogin()// rm表单的方式
                .loginPage("/login")//登录页面路径
                .loginProcessingUrl("/doLogin")
                //自定义登录请求地址
                .defaultSuccessUrl("/hello")
                .usernameParameter("loginName")
                .passwordParameter("loginPassword")
                .permitAll(true)//不拦截
                .and()
                .csrf()//记得关闭
                .disable()
                .sessionManagement().
                 maximumSessions(1) //需要这个字段设置为1
                .maxSessionsPreventsLogin(true);
    }
复制代码

org.springframework.security.web.session.ConcurrentSessionFilter#doFilte

复制代码
  private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //获取当前session
        HttpSession session = request.getSession(false);
        if (session != null) {
            //根据session id 从sessionRegistry 获取sessionInfo
            SessionInformation info = this.sessionRegistry.getSessionInformation(session.getId());
            if (info != null) {
                //判断是否过期 如果过期则触发doLogout逻辑
                if (info.isExpired()) {
                    // Expired - abort processing
                    this.logger.debug(LogMessage
                            .of(() -> "Requested session ID " + request.getRequestedSessionId() + " has expired."));
                    doLogout(request, response);
                    this.sessionInformationExpiredStrategy
                            .onExpiredSessionDetected(new SessionInformationExpiredEvent(info, request, response));
                    return;
                }
                // 刷新最后一次访问时间
                this.sessionRegistry.refreshLastRequest(info.getSessionId());
            }
        }
        chain.doFilter(request, response);
    }
复制代码

 

posted @   意犹未尽  阅读(419)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2020-11-10 spring源码阅读(二)-IOC之ClassPathXmlApplicationContext
点击右上角即可分享
微信分享提示