Question:
I need to validate the number of sessions that may exist, so that the user cannot log in to two places at the same time with the same credentials. Reading Spring Security documentation and posts, I arrived at the implementation below, but it doesn't work.
Has anyone had a similar problem, or is there some other type of validation I could do?
http.sessionManagement()
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
.expiredUrl("/entrar")
.sessionRegistry(sessionRegistry());
There is a project that I had made to test the functionality and the complete class can be seen in the link below like all the other configurations of the project that was made just for testing.
Answer:
Your configuration, according to the documentation, looks correct.
However, this could be a problem outside of this configuration. Spring, to understand that the same user is authenticated more than once, uses the equals()
and hashCode()
methods of its entity that represents the user (the one that implements the UserDetails
interface).
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 is 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;
}
}