Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable multiple logins for same user in spring security + spring boot

I have the below Spring Security configuration:

static SessionRegistry SR;
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/", "/forgotPwd", "/resetPwd").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/home")
            .failureUrl("/login?error")
            .permitAll()
            .successHandler(authenticationSuccessHandler) // autowired or defined below
            .and()
        .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessHandler(myLogoutSuccessHandler)
            .permitAll()
            .and()
        .sessionManagement()
            .maximumSessions(1)
            .maxSessionsPreventsLogin(true)
            .sessionRegistry(SR);
}

@Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
    return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
}

I was expecting sessionManagement().maximumSessions(1) to disable multiple login for the same user. It is working, but first user logout the application, so I am trying login in another browser but it showing This account is already using by someone.

Kindly request you to let me know where its going wrong.

like image 205
Durga Avatar asked Jul 25 '26 10:07

Durga


1 Answers

Remove your httpSessionEventPublisher and SessionRegistry

Try this config:

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
      .authorizeRequests()
          .antMatchers("/", "/forgotPwd", "/resetPwd").permitAll()
          .anyRequest().authenticated()
          .and()
      .formLogin()
         .loginPage("/login")
         .defaultSuccessUrl("/home")
         .failureUrl("/login?error")
         .permitAll()
         .and()
      .sessionManagement()
         .maximumSessions(1);
}

You can set the session timout in the application.properties

server.session.timeout= # Session timeout in seconds.
like image 162
Pär Nilsson Avatar answered Jul 27 '26 00:07

Pär Nilsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!