限制每个用户的最大并发会话

时间:2021-05-04 12:49:25

标签: java spring spring-security spring-session

你好团队我正在尝试设置每个用户的并发会话限制。我试图使用会话管理来限制它,但它没有按预期工作。我曾尝试将最大会话数设置为 1,但我可以拥有 1 个以上的活动会话。 请找到配置

http.csrf().disable()

            // take all the default security headers
            .headers()

            .contentTypeOptions().and()

            .xssProtection().and()

            .cacheControl().disable().addHeaderWriter(new StaticAndDynamicCacheControlHeaderWriter(cacheTimeDays))

            .httpStrictTransportSecurity().and()

            // add X-Frame-Options: SAMEORIGIN
            .frameOptions().sameOrigin().and()

            // Un-authenticated calls
            .authorizeRequests()
            .antMatchers("/api")
            .permitAll()

            .antMatchers("/api")
            .access("authenticated or hasIpAddress('localhost')").and()

            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler).and()

            // Login configuration - the default action here is POST.
            .formLogin().permitAll().loginProcessingUrl(LOGIN_LOGOUT_URI).successHandler(authLoginSuccessHandler).failureHandler(authLoginFailureHandler)
            .and()

            // Logout configuration
            .logout().permitAll().logoutRequestMatcher(new AntPathRequestMatcher(LOGIN_LOGOUT_URI, "DELETE")).logoutSuccessHandler(authLogoutSuccessHandler)
            .and()

            
            .addFilter(getJsonUsernamePasswordAuthenticationFilter())

            .authorizeRequests().antMatchers("/api/**").authenticated().and()

            .authorizeRequests().anyRequest().permitAll().and()

            .sessionManagement().maximumSessions(1).maxSessionsPreventsLogin(true).sessionRegistry(sessionRegistry());

1 个答案:

答案 0 :(得分:1)

除了配置之外,您的应用程序似乎还有更多内容,因此如果您有一个小的可重现示例可能会有所帮助。但是在一个简单的应用程序中,我注意到除非您注册 HttpSessionEventPublisher,否则会话管理不会完全起作用。将以下内容添加到您的 @Configuration

        @Bean
        public HttpSessionEventPublisher httpSessionEventPublisher() {
            return new HttpSessionEventPublisher();
        }

有关并发会话的详细信息,请参阅 docs