Validation of quantity of sessions with spring boot and spring security

Asked

Viewed 348 times

4

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

Has anyone ever had a similar problem, or has some other kind of validation that I could do?

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

There is a project that I had done to test the functionality and the complete class can be seen in the link below as all other project settings that was done just for testing.

https://github.com/MaxwelDev/security/blob/master/src/main/java/edu/security/gp/config/WebSecurityConfig.java

1 answer

1

Its configuration, according to the documentation, seems correct.

But this could be a problem outside of this configuration. Spring, to understand that the same user is authenticated more than once, uses the methods equals() and hashCode() of your entity representing the user (the one that implements the interface UserDetails).

Make the correct implementation of these two methods, taking into account only the information that uniquely identifies each user. Probably, the information to be used for this ó the "login" of the user.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.