DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Component Tests for Spring Cloud Microservices
  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC

Trending

  • Building a Real-Time Change Data Capture Pipeline With Debezium, Kafka, and PostgreSQL
  • Web Crawling for RAG With Crawl4AI
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  1. DZone
  2. Coding
  3. Frameworks
  4. How Spring Security Concurrent Session Control Works: Part 1

How Spring Security Concurrent Session Control Works: Part 1

In this post, we will understand how a Spring Security concurrent session control works and how to customize it for a clustered environment.

By 
Mohammed ZAHID user avatar
Mohammed ZAHID
DZone Core CORE ·
May. 13, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
13.7K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

Spring security provides a mechanism to control and limit the maximum number of single-user open sessions. This mechanism prevents users from exceeding the number of allowed simultaneous connections. For example, Netflix limits the number of screens you can watch at the same time according to your subscription plan.

In part 1, we will understand how this mechanism works, how to use it, and being aware of the default spring security implementation limitations. In part 2, we will see how to overcome those limitations in a clustered environment.

How It Works

In this section, we will focus on the classes responsible for concurrent session management in Spring Security rather than authentication management and events publishing. So in order to simplify the explanation, all the authentication mechanism including the authentication manager, the authentication provider, the authentication event publisher... will be represented by the AuthenticationManager.

  1. When a user authenticates successfully, the AuthenticationManager sends an event to the ConcurrentSessionControlAuthenticationStrategy.
  2. The ConcurrentSessionControlAuthenticationStrategy requests the SessionRegistery for all the open sessions of the authenticated user.
  3. The ConcurrentSessionControlAuthenticationStrategy checks if the number of open sessions, including the current one, exceeds the maximum number of allowed sessions. If not exceeded, the processing ends at this stage allowing the user to access the application.
  4. If the limit is exceeded, the ConcurrentSessionControlAuthenticationStrategy checks the value of configuration parameter exceptionIfMaximumExceeded:
    1. If true, the ConcurrentSessionControlAuthenticationStrategy throws an exception preventing the user from login into the application.
    2. If false, the ConcurrentSessionControlAuthenticationStrategy expires the oldest session of the authenticated user and allows him to access the application.

Sequence Diagram

How to Use It

Project Preparation

If you are familiar with Spring Boot and Spring Security you can build your own test project, if not you can follow the steps described in this post: Spring Security 4 for Spring MVC Using Spring Data JPA and Spring Boot.

Concurrent Session Control Configuration

The code below shows how to configure the session control by creating two beans bean of types SessionRegisteryImpl and ConcurrentSessionControlAuthenticationStrategy respectively; and setting the maximum number of sessions to 3 and the parameter exceptionIfMaximumExceeded value to true. So if a user authenticates more than three times he will be rejected.

Java
 







 
1
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
2
 
          
3
    ...
4
      
5
    @Bean
6
    public SessionRegistry sessionRegistry(){
7
        return new SessionRegistryImpl();
8
    }
9
 
          
10
  
11
    @Bean
12
    public SessionAuthenticationStrategy sessionAuthenticationStrategy(){
13
        ConcurrentSessionControlAuthenticationStrategy sessionAuthenticationStrategy= new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry());
14
        sessionAuthenticationStrategy.setMaximumSessions(3); // Set the max to 3
15
        sessionAuthenticationStrategy.setExceptionIfMaximumExceeded(true);// throw exception if max exceeded
16
        return sessionAuthenticationStrategy;
17
    }
18
  
19
 
          
20
    @Override
21
    protected void configure(HttpSecurity http) throws Exception {
22
        ...
23
        http
24
          .sessionManagement()
25
          .sessionAuthenticationStrategy(sessionAuthenticationStrategy());
26
        ...
27
    }
28
 
          
29
    ...
30
}



Limitations

The default implementation of SessionRegistery uses volatile storage because it stores the session information in the memory. The code below shows a part of the class implementation where we can see that the session information is stored in a ConcurrentMap. So if the server restarts that information will be lost and the user can authenticate again even if he exceeds the session limit.

Java
 




xxxxxxxxxx
1
10


 
1
public class SessionRegistryImpl implements SessionRegistry, ApplicationListener<AbstractSessionEvent> {
2
    ...
3
  
4
    // <principal:Object,SessionIdSet>
5
    private final ConcurrentMap<Object, Set<String>> principals;
6
   
7
    // <sessionId:Object,SessionInformation>
8
    private final Map<String, SessionInformation> sessionIds;
9
    ...
10
}



Another limitation is related to the use of the default implementation in a cluster. Since there is no synchronization between the different cluster nodes, each node will manager the concurrent sessions separately.  So the users can be authenticated in each node until reaching the limit. For example, if the maximum number of authorized sessions is M and we have N nodes, a user can authenticate successfully M times in each node so he can have MxN simultaneous open sessions.

Spring Framework Spring Security Session (web analytics)

Opinions expressed by DZone contributors are their own.

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Component Tests for Spring Cloud Microservices
  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!