我正在嘗試使用非 xml Spring Security 建立并發會話控制,因此如果用戶已經在另一臺設備上登錄,則他無法登錄。我用過.sessionManagement() .maximumSessions(1) .maxSessionsPreventsLogin(true),但使用 Chrome 和 Firefox 我仍然可以同時登錄。我已嘗試按照另一篇文章HttpSessionEventPublisher的說明進行配置,但我仍然能夠同時登錄。這是我的WebSecurityConfigurerAdapter:@Configurationpublic 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,但第二次并發登錄成功,我希望它會顯示錯誤。
1 回答

www說
TA貢獻1775條經驗 獲得超8個贊
在創建會話時,會話注冊表比較對象UserDetails以檢查是否已經存在該主體的會話。
由于您使用的是自定義 UserDetails 服務DinamicaUserDetailsService,因此您應該覆蓋 hashcode 和 equals 方法以確保它們與同一用戶匹配。例如,您可以比較用戶 ID 或用戶的任何其他唯一屬性。
@Override
public boolean equals(Object user) {
if(user == null) return false;
return (user.getId() == getId());
}
添加回答
舉報
0/150
提交
取消