Validation of number of sessions with spring boot and spring security

3

I need to validate the number of sessions that may exist, so that the user can not log in to two places at the same time with the same credentials. Reading the Spring Security documentation and posts, I got the implementation below, but it does not work.

Has anyone ever had a similar problem, or is there any other kind of validation I could do?

 http.sessionManagement()
                .maximumSessions(1)
                .maxSessionsPreventsLogin(true)
                .expiredUrl("/entrar")
                .sessionRegistry(sessionRegistry());

There is a project that you have done to test the functionality and the entire class can be seen in the link below as all other project settings that were made just for testing.

link

    
asked by anonymous 16.01.2018 / 21:12

1 answer

0

Your configuration, according to the documentation, seems correct.

However, this may be a problem out of this setting. Spring, to understand that a same user is authenticated more than once, uses the equals() and hashCode() methods of its entity representing the user (the one that implements the UserDetails interface).

Correctly implement these two methods, taking into account only information that uniquely identifies each user. Probably the information to be used for this is the user's login.

Example:

public class GpUserDetails implements UserDetails, Serializable {

    // código

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof GpUserDetails) {
          return login.equals( ((GpUserDetails) obj).getLogin() );
        }
        return false;
    }

    @Override
    public int hashCode() {
        return login != null ? login.hashCode() : 0;
    }
}
    
13.09.2018 / 14:06