gpt4 book ai didi

java - 无法在 spring-boot 中使用 maxSessions 和 maxSessionsPreventsLogin 设置并发 session 控制

转载 作者:行者123 更新时间:2023-12-02 04:56:12 36 4
gpt4 key购买 nike

我正在尝试使用非 xml Spring Security 建立并发 session 控制,因此如果用户已经在另一个设备中登录,则他无法登录。我使用了 .sessionManagement() .maximumSessions(1) .maxSessionsPreventsLogin(true),但使用 Chrome 和 Firefox 我仍然可以同时登录。

我已尝试按照 another post 的指示配置 HttpSessionEventPublisher ,但我仍然可以同时登录。

这是我的WebSecurityConfigurerAdapter:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccessDeniedHandler accessDeniedHandler;

@Autowired
UsuarioRepository usuarioRepository;

@Bean
public UserDetailsService mongoUserDetails() {
return new DinamicaUserDetailsService();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetailsService userDetailsService = mongoUserDetails();
auth.userDetailsService(userDetailsService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/",
"/home",
"/about",
"/registro",
"/session-error",
"/img/**",
"/img/*").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll()
.invalidateHttpSession(true)
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/session-error")
.maxSessionsPreventsLogin(true);
}

}

如果我在 Firefox 中尝试登录 Chrome,但第二次并发登录成功,我预计会显示错误。

最佳答案

创建 session 时, session 注册表会比较 UserDetails 的对象以检查该主体是否已存在 session 。

由于您使用的是自定义 UserDetails 服务 DinamicaUserDetailsS​​ervice,因此您应该重写 hashcode 和 equals 方法以确保它们与同一用户匹配。例如,您可以比较用户 ID 或用户的任何其他唯一属性。

@Override
public boolean equals(Object user) {
if(user == null) return false;
return (user.getId() == getId());
}

关于java - 无法在 spring-boot 中使用 maxSessions 和 maxSessionsPreventsLogin 设置并发 session 控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56409898/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com