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

假如想象 提交于 2021-01-28 01:28:57

问题


I have the below spring 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.


回答1:


You should try to invalid user session on logout with and/or delete cookies if you have one.

.logout().deleteCookies(...).invalidateHttpSession(true)



回答2:


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.


来源:https://stackoverflow.com/questions/44155608/disable-multiple-logins-for-same-user-in-spring-security-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!