spring-boot - 在 spring boot 和 OAuth2 应用程序中禁用同一用户的多次登录

标签 spring-boot oauth-2.0 netflix-zuul

我的微服务架构应用程序使用添加了 Oauth2 安全功能的 zuul api-gateway。现在,我可以在多个 session 中使用同一用户登录(我的意思是多个浏览器和多台机器)。所以我想限制同一用户的多次登录。

我使用下面的代码来限制同一用户登录。当我执行 oauth 注销时,此代码完美运行。但是当用户登录并关闭浏览器或清除浏览器 cookie 时,我遇到了问题。

static SessionRegistry sessionRegistry;

@Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.csrf().disable().authorizeRequests().antMatchers("/login", "/logout").permitAll().anyRequest()
        .authenticated().and().formLogin().loginPage("/login")
        .failureHandler(loginAuthenticationFailureHandler).permitAll().and().logout().and().authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .sessionManagement()
        .maximumSessions(1)
        .maxSessionsPreventsLogin(true)
        .sessionRegistry(sessionRegistry);
    }

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

任何人都可以帮助我如何在浏览器关闭和 cookie 清除时实现这个单用户 session 注销,或者是否有任何单独的程序来开发此功能。

最佳答案

我尝试使用相同的方法来实现使用 sessionManagement 配置,但它对我不起作用,在我的情况下,我只需要删除多重登录,关闭新登录或以前的登录,使用 InMemoryTokenStore 的扩展执行此操作。

@Component
public class ResetTokenStore extends InMemoryTokenStore {

 @Override
 public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    OAuth2AccessToken accessToken = super.getAccessToken(authentication);

    if(accessToken != null) {
        removeAccessToken(accessToken);
        removeRefreshToken(accessToken.getRefreshToken());
    }

    return null;
 }
}

基本上我做的就是强制更新token,每次都生成新的token登录,之前生成的accesstoken和refreshtoken都删除。

在扩展 AuthorizationServerConfigurerAdapter 的类中:

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    endpoints.tokenStore(tokenStore())
            .accessTokenConverter(accessTokenConverter())
            .reuseRefreshTokens(false)
            .userDetailsService(userDetailsService)
            .authenticationManager(authenticationManager);
}

@Bean
public TokenStore tokenStore() {
    return new ResetTokenStore();
}

关于spring-boot - 在 spring boot 和 OAuth2 应用程序中禁用同一用户的多次登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54744501/

相关文章:

spring - 基于 HTTPS/SSL 的 AWS ELB 背后的 Zuul

java - 使用 spring 和 mysql 将来自 UI 的数据保存为草稿

java - 带有 Spring Boot lambda 函数的 application.properties 的 AWS secret

java - 使用 Java 为 Blogger API 验证自己的 Google 帐户

node.js - React-Facebook-Login 和 Node.js Express

Zuul网关异常中的java.net.URI编码异常

Spring Boot - 应用程序无法使用类路径启动

java - spring-boot web应用程序无法启动: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

javascript - 调用身份服务器 token 端点

java - 具有反向代理的 Spring SAML - 响应的响应字段与发送的消息不对应