在spring security + spring boot中禁用同一用户的多次登录

时间:2017-05-24 10:22:12

标签: java spring spring-boot login spring-security

我有以下弹簧配置: -

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());
  }

我期待sessionManagement().maximumSessions(1)禁用同一用户的多次登录。它正在运行,但首先是用户logout应用程序,所以我尝试在另一个浏览器中登录,但它显示This account is already using by someone

请您告诉我哪里出了问题。

2 个答案:

答案 0 :(得分:0)

删除httpSessionEventPublisherSessionRegistry

试试这个配置:

@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);
}

您可以在application.properties

中设置会话时间
server.session.timeout= # Session timeout in seconds.

答案 1 :(得分:0)

如果你有cookie,你应该尝试在注销时使用和/或删除cookie无效的用户会话。

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