我正在尝试使用非 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
	提交
		取消
	