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:

Control the Session with Spring Security

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.

Similar Reads

Implementation of Control the Session with Spring Security

Below are the implementation steps to control the session with Spring Security....

Contact Us