Control the Session with Spring Security
Last Updated :
15 May, 2024
Spring Security is a scalable authentication control system, the de facto standard for protecting Spring-based applications. One of the main features is its consistency management capability which is important for the state between HTTP client and HTTP server. Proper session management is essential to secure application accessibility and user communication.
Session management in Spring Security can involve ensuring that only authenticated users can access their sessions, managing how they are utilized, and protecting against common exploits like session fixation, hijacking, and unauthorized access.
Key terminologies:
- Session Creation Policies:
- Always: The session will always be created if one does not exist.
- Never: The framework will never create the session but it will use one if it already exists.
- If_Required: Spring Security will only create the session when required(default).
- Stateless: No session will be used and created by Spring Security.
- Concurrent Session Control: It can limits the number of the concurrent sessions the user can have. It can helps prevent the attackers from hijacking an existing session.
- Session Fixation Protection: Spring Security can provides the session fixation protection by the changing the session ID after the user logs in.
- Invalidating Session on Logout: It can ensures that the session is invalidated when the user logs out and protecting against the session reuse.
- Concurrent Session Control: The feature of the Spring Security that can limits the number of the simultaneous sessions the user can have active. It can helps the prevent session hijacking by the ensuring the user only logs in the from one place at the time.
- Session Fixation: The security vulberability where the attackers can hijack the users session. It can protects the against this by the changing the session ID upon the authentication.
- Invalidating Sessions: It can used to action of the terminating the session upon the user logout to the ensure that the session cannot be reused by the malicious actors.
Implementation of Control the Session with Spring Security
Below are the implementation steps to control the session with Spring Security.
Step 1: Create a new Spring Boot project using Spring Initializr and include the required dependencies as mentioned below:
- Spring Web
- Spring Security
- Lombok
- Spring DevTools
After the project creation done, the folder structure will be like the below image:.

Step 2: Open the application.properties file and add the configuration for the security username and password of the Spring Security application in the project.
spring.application.name=spring-security-session-management
spring.security.user.name=user
spring.security.user.password=user
Step 3: Create the Security Configuration class.
We will create the SecurityConfig class to configure Spring Security in the project. Go src > org.example.springsecuritysessionmanagement > config > SecurityConfig and put the below code.
Java
package org.example.springsecuritysessionmanagement.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.defaultSuccessUrl("/home", true)
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.and()
.sessionManagement()
.maximumSessions(1)
.maxSessionsPreventsLogin(true);
}
}
Step 4: Create the Controller class.
We will create the HomeController class that will create the secure REST API of the spring project.
Go to src > org.example.springsecuritysessionmanagement > controller > HomeController and put the below code.
Java
/**
* Controller class for handling requests related to home and login pages.
*/
package org.example.springsecuritysessionmanagement.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/home")
public String home() {
return "home";
}
@GetMapping("/login")
public String login() {
return "login";
}
}
Step 5: Main Class (No Changes are required)
Go to src > org.example.springsecuritysessionmanagement > SpringSecuritySessionManagementApplication and put the below code.
Java
package org.example.springsecuritysessionmanagement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSecuritySessionManagementApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecuritySessionManagementApplication.class, args);
}
}
Step 6: Create the HTML page and name it Home.html.
Go to src > main > resources > templates > Home.html and put the below.
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to the Home Page!</h1>
<p>You are now logged in!</p>
<a href="/logout">Logout</a>
</body>
</html>
pom.xml:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>spring-security-session-management</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-session-management</name>
<description>spring-security-session-management</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 6: Run the Application
Now, we will run the application then it will be start at port 8080.

Output:
API Endpoint:
http://localhost:8080/login
Sign in page:
Enter the Username and password of the application and click on sign button then if the credential is correct then it will redirect to the home page.
- Username: user
- Password: user

After login home page:

After session expired:
Similar Reads
Spring Security Integration with Spring Boot
Spring Security is a powerful and customizable authentication and access control framework for Java applications. It provides comprehensive security services for Java EE-based enterprise software applications. This article will integrate Spring Security with a Spring Boot application, covering confi
5 min read
Security with Spring Security and Spring Webflux
Spring WebFlux is a part of the Spring Framework that supports reactive programming, enabling non-blocking asynchronous request handling. When developing web applications with Spring WebFlux, securing the application is a crucial aspect to ensure unauthorized access is prevented. This article provid
3 min read
Spring Security with Maven
Spring Security is a powerful and highly customizable authentication access management system. This is standard for protecting Spring-based applications. Spring Security is a framework that focuses on authentication and authorization for Java applications. Spring Security is a robust framework with
5 min read
Testing Spring Security Auth with JUnit
Here we are going to learn how to use InMemoryDaoImpl to verify Spring security authentication using a JUnit test case and how to programmatically create a fully complete authentication object and then utilize it in an application. SecurityContextHolder: Spring security is built on the concept of a
4 min read
Some Important Terms in Spring Security
Spring Security is a powerful authentication and authorization framework used to secure Java-based web applications. It integrates easily with Spring Boot and provides advanced security mechanisms such as OAuth2, JWT authentication, role-based access control, and protection against threats like CSRF
3 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authenti
2 min read
Securing a Spring MVC Application with Spring Security
Securing web applications is crucial in today's world, where security threats are prevalent. Spring Security is a powerful, customizable authentication and access-control framework that is part of the larger Spring ecosystem. It helps secure Spring MVC applications by managing authentication, author
6 min read
Spring Security - Filter Chain with Example
Spring Security is a framework that allows a programmer to use JEE components to set security limitations on Spring-framework-based Web applications. In a nutshell, itâs a library that can be utilized and customized to suit the demands of the programmer. Because it is a part of the same Spring famil
6 min read
Spring Security - Set Password Strength and Rules
In modern web applications, securing user credentials plays a major role. Spring Security can provide a comprehensive framework to secure Spring-based applications. One of the crucial aspects of security is enforcing password strength and rules to prevent weak passwords which can be easily compromis
8 min read
Spring Security with LDAP Authentication
LDAP (Lightweight Directory Access Protocol) is widely used for identity and access management. It organizes data in a hierarchical structure, optimized for read-heavy operations. LDAP is advantageous due to its scalability and interoperability. In this article, we will create a simple authenticatio
7 min read