Spring Single Session Login

When you want to configure your application for single session login, that’s mean user can login to application only from one session. Normally even in google, they allow to login to the system from different browsers or devices; but if you want to limit this to a single browser/device/session; this is the way.

At the first time I was looking this solution from different sources, but couldn’t find. Finally I got this solution from a friend of mine and it works perfectly. This is how I did it.

Please follow below steps,

Step 01 – Update Security Configuration

You have to set below configuration to the spring security configuration.


.sessionManagement()
.invalidSessionUrl("/login")
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
.expiredUrl("/login")

Note : In above configuration we set the no of session to one and allow to prevent login when maximum no of session reached.

Then you have to add below bean as well.


@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
    return new HttpSessionEventPublisher();
}

Note : You can write a custom HttpSessionEventPublisher if you want, here I used the existing one which spring gives default.

Step 02 – Update UserDetails Implemented Domain

Now you have to find the domain which UserDetails implemented. (When Application configured with spring security,  we have to create a object which implements the UserDetails object)

Add below methods at end of the Domain class.


@Override
public boolean equals(Object otherUser) {
   if (otherUser == null)
   return false;
   else if (!(otherUser instanceof UserDetails))
   return false;
   else
   return (otherUser.hashCode() == hashCode());
}

@Override
public int hashCode() {
    StringBuffer sb = new StringBuffer();
    sb.append(this.emailAddress != null ? this.emailAddress : "");
    sb.append(this.userName != null ? this.userName : "");

    String hashCode = sb.toString();
    return hashCode.hashCode();
}

 

Leave a comment