我的微服务架构应用程序使用添加了 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/