Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Wednesday, April 10, 2024

How to limit Concurrent Login Sessions in a Java web application using Spring Security? Example

If you don't know, Spring security can limit the number of sessions a user can have in a Java web application. If you are developing a web application especially a secure web application in Java JEE then you must have come up with the requirement similar to many online banking portals have like only one session per user at a time or no concurrent session per user. If the user tries to open a new session then either an alert is shown or his previous session is closed. Even though you can also implement this functionality without using spring security but with Spring security, it's just a piece of cake with coffee :). 

You just need to add a couple of lines of XML in your spring security configuration file and you are done. In order to implement this functionality, you can use the <concurrency-control> tag.

You can configure a maximum number of the session your application support and then Spring security will automatically detect if user breach that limits and direct them to invalid session url you have specified with this tag e.g. to a logout page. 

Similar to this, Spring Security provides lots of Out of Box functionality a secure enterprise or web application needed for authentication, authorization, session management, password encoding, secure access, session timeout, etc. 

In our spring security example, we have seen how to do LDAP Authentication in an Active directory using spring security and in this spring security example we will see how to limit the number of session users can have in Java web application or restricting concurrent user session.

By the way, if you are new to Spring framework then I also suggest you join a comprehensive and up-to-date course to learn Spring in depth. If you need recommendations, I highly suggest you take a look at Spring Framework 5: Beginner to Guru, one of the comprehensive and hands-on course to learn modern Spring. It' also most up-to-date and covers Spring 5. 

Spring Security Example: Limit Number of User Session

As I said it’s simple and easy when you use a spring security framework or library. In fact, it is all declarative and no code is required to enable the concurrent session to disable the functionality

You will need to include the following xml snippet in your Spring Security Configuration file mostly named as applicaContext-security.xml. You can name the file whatever you want but just make sure you use the same name in all relevant places. 

If you are not sure how to enable Spring Security in Java web application, check that article first. 

Here is sample spring security Example of limiting user session in Java web application:

<session-management invalid-session-url="/logout.html">
    <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />

As you see you can specify how many concurrent sessions per user is allowed, a most secure system like online banking portals allows just one authenticated session per user. 

The Max-session specifies how many concurrent authenticated session is allowed and if error-if-maximum-exceeded set to true it will flag an error if a user tries to login into another session.

For example, if you try to log in twice from your browser to this spring security application then you will receive an error saying "Maximum Sessions of 1 for this principal exceeded" as shown below:

Spring security concurrent session control example

You can even specify a URL where the user will be taken if they submit an invalid session identifier that can be used to detect session timeout. The session-management element is used to capture the session related stuff. 

And, if you don't want to use XML configuration and what to do same thing in Java configuration then you can  create a class annotated with @Configuration and define beans for configuring session management. 

Here is the same example of limiting concurrent session using Java Configuration in Spring Framework:

import org.springframework.context.annotation.Configuration;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(HttpSecurity http) throws Exception {

In this example @Configuration marks the class as a configuration class and  @EnableWebSecurity enables Spring Security's web security support, and  SecurityConfig extends WebSecurityConfigurerAdapter, providing default security configurations.

In the configure(HttpSecurity http) we have defined the security requirements for our application. For example,  authorizeRequests() is used to specify authorization rules for various URLs in our application. Then  antMatchers("/logout.html").permitAll() is a rule allowing unrestricted access to the "/logout.html" URL without requiring any authentication.

Simialry, anyRequest().authenticated() is a rule which says that any request not matched by previous rules must be authenticated, meaning users need to log in to access those resources and sessionManagement() configures how sessions are managed in your application.

The invalidSessionUrl("/logout.html") sets the URL where users are redirected if their session is invalid or expired, in this case, directing them to the logout page and most importantly  maximumSessions(1) sets the maximum number of allowed sessions for a single user, and maxSessionsPreventsLogin(true) ensures that if a user tries to log in when they already have the maximum number of sessions, further login attempts will be prevented

This is just an example of what Spring security can add to your Java web application. It provides many such advanced and necessary features which can be enabled using some XML tag or annotations. 

If you are interested to learn more about advanced Spring security features, I suggest you go through the Learn Spring Security course by Eugen Paraschiv, which the most up-to-date online course on Spring Security and covers new security features from Spring Security 5 release. 

Spring Security Concurrent User Session example


spring security example - limit number of session in java J2EEThis code has a dependency on the spring-security framework. You need to download spring security jar like spring-security-web-3.1.0.jar and add it into application classpath.

This simple example of spring security shows the power of spring security, a small piece of xml snippet can add very useful and handy security feature in your Java web application. 

I strongly recommend using spring security for your new or existing Java web application created using Servlet JSP.

That’s all on how to limit the number of user sessions using spring security in Java web applications. Let me know if you face any issue while implementing this security feature in your project. 

Thanks for reading this article so far. If you find this Spring Security tutorial use then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P.S - If you like to learn from a book, then Spring Security in Action by Laurentiu Spilca is a good starting point. The content is not advanced enough for senior developers but for the junior and intermediate programmers, it's a great book.

P.S.S Also, If you are an experienced Java/JEE Program and want to learn Spring Security end-to-end, I recommend the Learn Spring Security course by Eugen Paraschiv, The definitive guide to secure your Java application. It's useful for both junior and experienced Java Web developers.


Anonymous said...

How does this work in a clustered environment?

danish said...

Cool Example, just few lines of code. Indeed looks like Spring Security is full of such great feature which just need configuration to make them active. I am loving Security Security :)

Sashika said...

Does this handle browser close or browser crash scenarios? If we set the max-sessions=1 and if we close the browser without logging off, can the user login again immediately?

Sindhuraj said...

@Sashika, it doesn't handle browser close scenario. If user closes its browser without logging off from application, his user session will be active on Server and all subsequent login from same user will be denied as "maximum active session is 1".

By the way this feature is called Spring Security Concurrent Session Control and available from Spring security 3.0 in declarative format as mentioned in this tutorial.

I agreed with Writer that this is the easiest way to implement Concurrent Session Control on any Java web application but this feature requires a central Session Repository and if you are running on Two cluster where Session replication is not available and both Cluster have there own session repository, you will end up with Concurrent multiple User session. I am not sure if you can customize this behavior by implementing your own Session Repository, If you have any idea please jump in.

Sourabh Ghose said...

@Sinduraj, The concurrentsessionfilter indeed does not work in a clustered environment with multiple web servers. In order to make this work you would have to write a custom SessionRegistry as described here:

Anonymous said...

how to enable Spring Security in case of browser close or browser crash scenario....??

Unknown said...

Im using spring 2 version the same code is not working for me.i cant migrate to spring 3 as im doing enhancement if i try to migrate from spring 2 to spring 3 it is very difficult for me.can any body help me to fined the solution

javin paul said...

Hello Neethu, what is the error you are getting? some more information would be helpful because its spring spring security feature not core spring framework.

Unknown said...

Hi Javin Paul,

After implementing your code I observed that if I login as specific user say admin in internet explorer then I am able to login into IE with same user but it does not allow to login with admin in another browser chrome vice -versa .please tell why does not work for the same browser

javin paul said...

@arnab, there is a setting for that which allow multiple active session, as discussed on my post how to control active session in Spring security. You can configure it depending upon your requirement.

Unknown said...

Hi Javin,

After implementing your below code

I observed that concurrent session of a user
is possible from same browser e.g same user can login multiple times from same browser how can I stop user from second time login from the same browser e.g IE if that user is already logged ?
How can stop concurrent login for a specific user the above code is common to all user ?
How can i throw custom error messages in spring-security if the user tries to login for second time?

Post a Comment