Spring Security maxSession doesn't work

前端 未结 2 2029
庸人自扰
庸人自扰 2021-01-05 23:50

I want to prevent login when user exceed maxSession count. For example every user can login once. And then if logged user try another login system should disable login for

2条回答
  •  时光说笑
    2021-01-06 00:32

    I had the same problem and it was originated in my UserDetails implementation:

    ConcurrentSessionControlAuthenticationStrategy Line 93:

    final List sessions = sessionRegistry.getAllSessions(
            authentication.getPrincipal(), false);
    

    SessionRegistryImpl Line 74:

    final Set sessionsUsedByPrincipal = principals.get(principal);
    
    if (sessionsUsedByPrincipal == null) {
        return Collections.emptyList();
    }
    

    In the session registry searches inside the "principals" list for a UserDetails object. So you need to override equals and hashcode in your UserDetails implementation, otherwise, it will view them as separate objects and thus always return an emptyList.

    Example:

    public class ApplicationUser implements UserDetails {
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof ApplicationUser)) return false;
            ApplicationUser that = (ApplicationUser) o;
            return username.equals(that.username) &&
                    email.equals(that.email) &&
                    password.equals(that.password);
        }
    
        @Override
        public int hashCode() {
            return Objects.hash(username, email, password);
        }
    
    }
    

提交回复
热议问题