Monday, December 01, 2014

Spring Security - Concurrent Session Control

Steps to limiting one session per user across multiple browsers or devices.
1. web.xml
    <listener>         <listener-class>               org.springframework.security.web.session.HttpSessionEventPublisher         </listener-class>     </listener>
2. UserDetails class - make sure to implement hashCode() and equals() methods. Also implement toString() for convenience to see better log messages.
public class MyUser implements Serializable, UserDetails { ... //code omitted fro brevity @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (this.getClass() != obj.getClass()) { return false; } MyUser other = (MyUser) obj; if (this.email == null && other.email != null) { return false; } if (!email.equals(other.email)) { return false; } return true; } @Override public String toString() { return "user [" + email + "]"; }
3. security-context.xml
<!-- Allow max 1 session per user -->          <sec:session-management invalid-session-url="/login?login_error=sessionExpired" session-authentication-error-url="/login?login_error=alreadyLoggedIn">
            <sec:concurrency-control error-if-maximum-exceeded="false" expired-url="/login?login_error=sessionExpiredDueToDuplicateLogin" max-sessions="1">
        </sec:concurrency-control></sec:session-management>
4. login.jsp
&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core"   prefix="c"%&gt;
&lt;%@ taglib uri="http://www.springframework.org/tags" prefix="s"%&gt;
<c:if test="${not empty param.login_error}">
    <c:choose>
        <c:when test="${param.login_error eq 'sessionExpired'}">
            <s:message code="login.error.sessionExpired">
        </s:message></c:when>
        <c:when test="${param.login_error eq 'sessionExpiredDueToDuplicateLogin'}">
            <s:message code="login.error.sessionExpiredDueToDuplicateLogin">
        </s:message></c:when>
        <c:otherwise>
            <s:message code="login.error">
        </s:message></c:otherwise>
    </c:choose>
</c:if>
Reference: http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity-single.html#ns-session-mgm 

No comments:

Post a Comment