I'm triying to stablish concurrent session control with non-xml Spring Security, so a user can´t login if he is already logged in another device. I used .sessionManagement() .maximumSessions(1) .maxSessionsPreventsLogin(true), but using chrome and firefox I still can log in concurrently.

I have tried configuring HttpSessionEventPublisher as instructed by other post, but still able to log in concurrently.

This is my 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)
         ;

}

I expect been shown an error while triying to log in in chrome while i'm still logged in firefox, but second concurrent logging is sucessfull.

1 Answers

0
Agam On

While creating the session, session registry compare the the object of UserDetails to check if there is already a session for that principal.

Since you are using a custom UserDetails service DinamicaUserDetailsService, you should override hashcode and equals method to make sure they are matched for same user. For example you can compare user id or any other unique attribute of user.

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