Authentication and Authorization in Spring Boot 3.0 with Spring Security
Last Updated :
24 Mar, 2025
In Spring Security 5.7.0, the spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes in Spring Security. So in this article, we will understand how to perform spring security authentication and authorization using Spring Boot 3.0.
Demo Project
Step 1: Create a New Spring Boot Project in Spring Initializr
To create a new Spring Boot project, please refer to How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA. For this project choose the following things
- Project: Maven
- Language: Java
- Packaging: Jar
- Java: 17
Please choose the following dependencies while creating the project.
- Spring Web
- Spring Security
Below is the complete pom.xml file. Please cross-verify if you have missed some dependencies
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.1.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Security Test for Testing Security Configurations -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot Maven Plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Step 2: Create a UserController
Go to the src > main > java > controller and create a class UserController and put the below code. In this, we have created a simple REST API in our controller class.
Java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth")
public class UserController {
@GetMapping("/welcome")
public String welcome() {
return "Welcome, this endpoint is not secure";
}
@GetMapping("/user/userProfile")
@PreAuthorize("hasRole('USER')") // Use hasRole for role-based access control
public String userProfile() {
return "Welcome to User Profile";
}
@GetMapping("/admin/adminProfile")
@PreAuthorize("hasRole('ADMIN')") // Use hasRole for role-based access control
public String adminProfile() {
return "Welcome to Admin Profile";
}
}
Step 3: Create a SecurityConfig Class
Go to the src > main > java > config and create a class SecurityConfig and put the below code. This is the new changes brought in Spring Boot 3.0.
Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
// User Creation
@Bean
public UserDetailsService userDetailsService(PasswordEncoder encoder) {
// InMemoryUserDetailsManager setup with two users
UserDetails admin = User.withUsername("Amiya")
.password(encoder.encode("123")) // <-- Encode the password
.roles("ADMIN", "USER")
.build();
UserDetails user = User.withUsername("Ejaz")
.password(encoder.encode("123")) // <-- Encode the password
.roles("USER")
.build();
return new InMemoryUserDetailsManager(admin, user);
}
// Configuring HttpSecurity
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // Disable CSRF for simplicity
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/welcome").permitAll() // Permit all access to /auth/welcome
.requestMatchers("/auth/user/**").authenticated() // Require authentication for /auth/user/**
.requestMatchers("/auth/admin/**").authenticated() // Require authentication for /auth/admin/**
)
.formLogin(withDefaults()); // <-- Use withDefaults() for form-based login
return http.build();
}
// Password Encoding
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Test the Application
Now run your application and test it out. Hit the following URL
http://localhost:8080/auth/welcome
You can access this endpoint without any authentication as it is not secured.

Now, hit the following URL:
http://localhost:8080/auth/user/userProfile
If Not Logged In: You will be redirected to the below URL:
http://localhost:8080/login
Output:

After putting the correct Username and Password you can access your endpoint. Put this Username and Password
- Username: Ejaz
- Password: 123
And you will get the output screen like this,

After logging in with the correct credentials, you will be able to access this endpoint if your role includes USER
.
Similarly, you can hit and try other Users and play with it.
Similar Reads
Spring Boot - OAuth2 Authentication and Authorization
OAuth2 is a widely-used protocol for authorization that enables applications to securely access resources on behalf of users. When combined with Spring Boot, OAuth2 facilitates authentication and authorization for both REST APIs and web applications. This article will walk you through setting up OAu
7 min read
API Gateway Authentication and Authorization in Spring Boot
In modern web applications, securing the communication between the clients and backend services is crucial. The API Gateway can serves as the reverse proxy and managing the client requests, and routing them to the appropriate the backend services. It enhance the security, we can implement the authen
12 min read
Spring Boot 3.0 - JWT Authentication with Spring Security using MySQL Database
In Spring Security 5.7.0, the spring team deprecated the WebSecurityConfigurerAdapter, as they encourage users to move towards a component-based security configuration. Spring Boot 3.0 has come with many changes in Spring Security. In this article, we'll learn how to implement JWT authentication and
8 min read
Spring Security - Custom Form Login with Database Authentication
In this article, Spring Security Basic Authentication, we have demonstrated the Basic Authentication using In-Memory Authentication. But what if we are required to authenticate the user from the database? And also what if we are required to login with the custom form? In this article, we will explai
8 min read
Spring Security - Login for a Spring Web App â Error Handling and Localization
In modern web applications, security is crucial, and Spring Security provides a powerful and customizable authentication and access control framework for Java applications. This article guides you through setting up a Spring Boot application with Spring Security, focusing on login functionality, err
15 min read
Securing Spring Boot API With API Key and Secret
In Web applications, securing the APIs is critical. One of the common methods of securing the APIs is by using API keys and secrets. This ensures that only the authorized clients can access the API endpoints. This article can guide you through the process of securing the Spring Boot API using the AP
6 min read
Prevent Brute Force Authentication Attempts with Spring Security
Brute force attacks are a common threat where an attacker tries multiple combinations of usernames and passwords to gain authorized access to the system. To protect against such attacks, it is crucial to implement mechanisms that can detect and block repeated failed login attempts. Spring Security c
10 min read
Spring Security - Two Factor Authentication
Two-factor authentication (2FA) is a security method that requires users to provide two forms of authentication to access their accounts. These forms of authentication typically include something the user knows (such as a password or PIN) and something the user has (such as a mobile device or hardwa
10 min read
Securing Spring Cloud Config Server with Basic Authentication
Spring Cloud Config Server provides externalization for distributed systems. With the increasing importance of microservices, centrally managing configurations becomes crucial. Securing this configuration server is equally important to prevent unauthorized access. Basic authentication is a simple an
4 min read
Difference between Authentication and Authorization in LLD | System Design
Two fundamental ideas in system design, particularly in low-level design (LLD), are authentication and authorization. While authorization establishes what resources or actions a user is permitted to access, authentication confirms a person's identity. Both are essential for building secure systems b
4 min read