Spring Security Concurrency Control Example

In this example, we will see how to use Spring Security to add support for concurrent session control to limit the number of active sessions a user can have.

 

1. Technologies used

  • Spring Security 3.2.5.RELEASE
  • JSF 2.2.8
  • MySQL 5
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7
  • Tomcat 7.0

 

2. Project structure

SpringSecurityConcurrencyControlExample

 

3. Project dependencies

We add JSF 2 and Spring dependencies in our project’s pom.xml :

 

4. Spring Security configuration

We set the default failure URL:

We have specified a custom implementation of the SimpleUrlAuthenticationFailureHandler class in order to extract the “cause” of failure and print it to the user.

 

We set the default target URL when authentication is successful:

 

The authenticationEntryPoint redirects the user to the login page when the server sends back a response requiring authentication:

 

To handle concurrent session control, we need to set two properties: sessionRegistry, which points to an instance of SessionRegistryImpl, and expiredUrl which points to the page to display when a session has expired:

 

We are going to use the CompositeSessionAuthenticationStrategy bean to define a concurrent control strategy that will prevent a user from concurrently authenticating to the same application more than one time. Here is the complete Spring Security configuration:

File : spring-security.xml

 

5. Authentication failure handler

KeyAuthFailureHandler.java

We set the failure cause to the status parameter to display it on the login page when authentication fails.

 

6. login page

login.xhtml

When authentication fails, the error message is displayed using the status parameter.

 

7. web.xml

We need to add the HttpSessionEventPublisher listener to our web.xml; It is used to keep Spring Security informed about session life cycle events.

 

8. Test It

We will try to authenticate to our application two times. But to test correctly, we need two different browsers or using two different profiles on the same browser:

Open Firefox browser (or the first browser profile) and go to the login page, then authenticate using the credentials [Walid/111]

SpringSecurityConcurrencyControlExample0

Open Chrome browser (or the second browser profile) and go to the login page, then provide the same credentials [Walid/111] and click on the submit button:

SpringSecurityConcurrencyControlExample1

The second login attempt has been rejected. Because we cannot have more than one session.

To authenticate successfully, we just need to logout from the first login page.

 

Download source code