Spring Security is a framework used to secure Spring and Spring Boot applications. It provides features like authentication, authorization, password protection, session management, and security filters to protect applications from unauthorized access and cyber attacks. Spring Security integrates easily with Spring Boot and helps developers build secure enterprise-level applications.
- Protects applications from common security threats.
- Supports role-based access control and secure login systems.
Importance of Spring Security
Security is important in web applications to protect user data and restrict unauthorized access.
- Prevents unauthorized users from accessing protected resources.
- Secures sensitive information such as passwords and user details.
- Helps protect applications from attacks like CSRF and session hijacking.
- Supports secure communication using HTTPS.
- Improves trust and reliability of enterprise applications.
Core Concepts of Spring Security
Spring Security provides important security features to protect web applications from unauthorized access and attacks. It mainly focuses on authentication, authorization, request filtering, and secure user management.
Authentication
Authentication is the process of verifying the identity of a user before allowing access to the application. Spring Security checks user credentials like username and password during login.
- Verifies user identity using login credentials.
- Supports in-memory, JDBC, LDAP, and OAuth2 authentication.
Authorization
Authorization determines what resources or actions a user can access after successful authentication. Access is controlled using roles and permissions.
- Restricts access based on roles and permissions.
- Protects URLs, APIs, and application resources.
Security Filters
Security filters intercept HTTP requests and apply security checks before requests reach the application. They help enforce authentication and authorization rules.
- Handles login, logout, and request validation.
- Provides CSRF protection and session management.
Security Providers
Security providers are responsible for validating user credentials and managing authentication logic. They connect Spring Security with different authentication sources.
- Supports database, LDAP, and OAuth2 authentication providers.
- Manages users, roles, and authentication details.
Setting up Spring Security in Spring Boot 3.0
Step 1: Create a Spring Boot Project
Create a Spring Boot project using Spring Initializr or any IDE. Add the following dependency:
- Spring Web
- Spring Security
Adding Spring Security dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Step 2: Create REST Controller
Create a controller class to define secured and public endpoints.
- Use @RestController to create REST APIs.
- Use @RequestMapping("/home") for base URL mapping.
- Create separate endpoints for admin, normal, and public users.
HomeController
package com.spring.security.controllers;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/home")
public class HomeController {
// Handler Methods
@GetMapping("/normal")
public ResponseEntity<String> normalUser(){
return ResponseEntity.ok("I am User");
}
@GetMapping("/admin")
public ResponseEntity<String> adminUser(){
return ResponseEntity.ok("I am Admin");
}
@GetMapping("/public")
public ResponseEntity<String> publicUser(){
return ResponseEntity.ok("I am Public User");
}
}
Step 3: Create Security Configuration Class
Create a configuration class to define Spring Security settings.
- Annotate the class with @Configuration.
- Create a PasswordEncoder bean using BCryptPasswordEncoder.
- Configure users using InMemoryUserDetailsManager.
Configuring Security Filters
package com.spring.security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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;
@Configuration
public class SecurityConfig {
// Password Encoder
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// User configuration
@Bean
public UserDetailsService userDetailsService() {
UserDetails normalUser=User
.withUsername("Pranay")
.password(passwordEncoder().encode("password"))
// roles
.roles("NORMAL")
.build();
UserDetails adminUser=User
.withUsername("Admin")
.password(passwordEncoder().encode("password"))
.roles("ADMIN")
.build();
InMemoryUserDetailsManager inMemoryUserDetailsManager= new InMemoryUserDetailsManager();
inMemoryUserDetailsManager.createUser(normalUser);
inMemoryUserDetailsManager.createUser(adminUser);
return inMemoryUserDetailsManager;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{
httpSecurity.csrf().disable()
.authorizeHttpRequests()
// Role based Authentication
.requestMatchers("/home/admin")
.hasRole("ADMIN")
.requestMatchers("/home/normal")
.hasRole("NORMAL")
.requestMatchers("/home/public")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin();
return httpSecurity.build();
}
}
Step 4: Configure User Authentication
Create users and assign roles.
- Use UserDetails objects for user information.
- Encode passwords before storing them.
- Use .roles("ADMIN") and .roles("NORMAL") for authorization
UserDetails adminUser = User
.withUsername("Admin")
.password(passwordEncoder().encode("password"))
.roles("ADMIN")
.build();
Step 5: Configure Security Filter Chain
Configure URL access rules using SecurityFilterChain.
- Use requestMatchers() for URL-based authorization.
- Use hasRole() for role-based access.
- Use permitAll() for public APIs.
Step 6: Run the Spring Boot Application
Run the application.
Output:




Best Practices for Spring Security Configuration
- Use strong passwords and encode them securely using PasswordEncoder.
- Use HTTPS to encrypt communication between client and server.
- Enable CSRF protection to prevent unauthorized requests.
- Implement proper session management to avoid session hijacking.
- Use role-based access control (RBAC) for secure resource access.
- Add Two-Factor Authentication (2FA) for extra account security.