尝试在同一浏览器中第二次登录时使用 Spring security 强制注销用户

问题描述 投票:0回答:1

我正在使用 Google Oauth 对我的应用程序的用户进行身份验证。 当用户尝试登录(使用同一浏览器上的新选项卡)而不注销时,我想强制从用户的第一个会话中注销该用户。

我在浏览器中看到第二次登录的新 JSESSIONID,但我仍然看到第一次登录的 cookie。 我还看到第一个登录用户的 HttpSession 中存储的属性。所以cookie和HttpSession肯定没有被清除,但我不知道第二次登录时第一次身份验证是否已失效。 你们中的任何人都可以指出我需要调用的方法,以便在用户尝试再次登录时强制从第一个会话中注销用户吗?我可以用同样的方法清除 cookie 并使 HttpSession 失效。

这是我当前使用 Oauth 的 Spring 安全代码。

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http
         .csrf()
         .disable()
         .authorizeRequests()     
         .antMatchers( "/error", "/login.html", "/images/**", "/styles/**")
         .permitAll()
         .antMatchers("/request.html").hasAnyAuthority("USER")
     .antMatchers(.....)
         .anyRequest().authenticated()
         .and()
         .logout()
         .invalidateHttpSession(true)
     .clearAuthentication(true)
     .deleteCookies("JSESSIONID","roles","username") 
         .logoutSuccessHandler(new LogoutSuccessHandler() {
             
                @Override
                public void onLogoutSuccess(HttpServletRequest request,                         HttpServletResponse response,
                        Authentication authentication) throws                           IOException, ServletException {
                    
                    
                        response.sendRedirect("/login.html");
                    
                }
         })
         .and()
         .oauth2Login(oauth2 -> oauth2.userInfoEndpoint(userInfo -> userInfo
                          .oidcUserService(this.oidcUserService())
                                 )
                 .loginPage("/login.html") 
                         .failureUrl("/loginFailure")
                         .successHandler(customOauth2SuccessHandler)
                     )
         
         ;
spring-security spring-security-oauth2
1个回答
0
投票

如果我理解这个问题,Spring Security 应该可以帮助你,

https://docs.spring.io/spring-security/reference/servlet/authentication/session-management.html#ns-concurrent-sessions

如果您希望对单个用户登录应用程序的能力进行限制,Spring Security 通过以下简单的添加即可开箱即用地支持此操作。首先,您需要将以下侦听器添加到您的配置中,以使 Spring Security 更新有关会话生命周期事件的信息:

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

并更新配置,

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
    http
        .sessionManagement(session -> session
            .maximumSessions(1)
        );
    return http.build();
}

这将防止用户多次登录 - 第二次登录将导致第一次登录无效。

该链接讨论了仅允许第一个会话等的更多配置(并提供了测试来验证)。

© www.soinside.com 2019 - 2024. All rights reserved.