1

Spring Boot Web MVC Allow one user at a time from anywhere, If he/she wants to login, then there will be forced login.

I have search a lot on internet, i found that i can do something like :

http.sessionManagement()
  .invalidSessionUrl("/invalidSession")
  .maximumSessions(1)
  .maxSessionsPreventsLogin(true)
  .sessionRegistry(sessionRegistry())

But this is not working, I am able to login from a different browser without any error.

I trying to solve this problem from last week but did not find any workable solutions.

Update

http.antMatchers("/", "/register/**", "/email/**","/captcha.png/**")
  .permitAll()
  .antMatchers("/login/**")
  .permitAll()// Basically I'm allowing parameters for login so
  // .antMatchers("/services/ownerTaxInformation/**")
  .permitAll()
  .antMatchers("/forgot/password/**", "/user/verify/**")
  .permitAll()
  .antMatchers("/user/resetPassword*")
  .hasAuthority("CHANGE_PASSWORD_PRIVILEGE")
  .anyRequest()
  .authenticated()
  .and()
  .addFilterBefore(jCaptchaAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class)
   .formLogin()
   .loginPage("/login")
   .permitAll().and()
   .csrf()
   .disable()
   .sessionManagement()
   .invalidSessionUrl("/invalidSession")
   .maximumSessions(1)
   .maxSessionsPreventsLogin(true)
   .sessionRegistry(sessionRegistry()).and()
   .sessionFixation()
   .none()
   .and()
   .logout()
   .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
   .logoutSuccessUrl("/")   
   .invalidateHttpSession(false)
   .deleteCookies("JSESSIONID")
   .permitAll();
Robert Christopher
  • 4,940
  • 1
  • 20
  • 21
Mandy
  • 1,103
  • 3
  • 17
  • 38

2 Answers2

0

you can create a filter(which will filter all url where you want one user at time) and then check if there is no user in sessionRegistry then user can access the url else invalidate user access. For accessing the list of all logged in users you need to inject SessionRegistry instance to your bean.

@Autowired
@Qualifier("sessionRegistry")
private SessionRegistry sessionRegistry;

here is helpful details about sessionRegistry retrieving the list of login users

Bhushan Uniyal
  • 5,575
  • 2
  • 22
  • 45
-2

Yes I have faced similar issue. I have fixed by the following snippet.

Inside configuration

@Override
public void configure(HttpSecurity http) throws Exception 
{
    http.

                authorizeRequests()

                  .and()
                  .sessionManagement()
                    .maximumSessions(1) // How many session the same user can have? This can be any number you pick
                    .expiredUrl("/login?expired")
                    .sessionRegistry(sessionRegistry);

}



@Bean(name = "sessionRegistry")
public SessionRegistry sessionRegistry() {
  return new SessionRegistryImpl();
}

@Autowired
@Lazy
private SessionRegistry sessionRegistry;
Sankar
  • 687
  • 1
  • 13
  • 25