Backend
6/16/2026
4 min read

Mastering Spring Security 7 with Spring Boot 4 : Secure Your First REST API

Mastering Spring Security 7 with Spring Boot 4 : Secure Your First REST API

Security is one of the most important aspects of modern application development. Every production system, whether it is a banking platform, an e-commerce application, a SaaS product, or a microservices ecosystem, requires proper authentication and authorization mechanisms to protect sensitive resources.

Spring Security is the de facto standard framework for implementing security in Java applications. It provides a comprehensive set of features that help developers secure REST APIs and web applications while following industry best practices.

In this series, we will learn Spring Security 7 using Spring Boot 4 and Java 21 from scratch to advanced production-level implementations. Every article will include definitions, real-world examples, code explanations, and practical recommendations used in enterprise applications.

Technology Stack

Framework

Version

Spring Boot

4.0.6

Spring Framework

7.0.7

Spring Security

7.0.5

Java

21 LTS


What is Spring Security?

Spring Security is a powerful framework that provides authentication, authorization, and protection against common security vulnerabilities.

It helps developers implement:

  • User authentication

  • Role-based access control

  • Password encryption

  • Session management

  • CSRF protection

  • Method-level security

  • JWT authentication

  • OAuth2 and OpenID Connect

  • Protection against common attacks

Spring Security integrates seamlessly with Spring Boot and follows modern security standards.

Why is Security Important?

Consider an Employee Management System.

Without security:

  • Anyone can access employee information.

  • Sensitive records may be modified by unauthorized users.

  • Confidential business data can be exposed.

With Spring Security:

  • Only authenticated users can access APIs.

  • Different roles receive different permissions.

  • Passwords are encrypted before storage.

  • Requests are validated before reaching business logic.

Security acts as a gatekeeper between users and application resources.

Adding Spring Security Dependency

Spring Boot 4 automatically manages the Spring Security version.

Add the following dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

This starter includes:

  • Authentication mechanisms

  • Authorization support

  • Security filters

  • Password encoders

  • Session management

  • Protection against common attacks

Creating a Simple REST API

Suppose we are building an Employee Service.

@RestController
@RequestMapping("/api")
public class EmployeeController {

    @GetMapping("/public")
    public String publicEndpoint() {
        return "Public API";
    }

    @GetMapping("/private")
    public String privateEndpoint() {
        return "Private API";
    }

}

Currently, both endpoints are unsecured.

Available APIs:

GET /api/public
GET /api/private

Configuring Spring Security

Spring Security 7 uses SecurityFilterChain to configure security.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http)
            throws Exception {

        return http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/api/public")
                        .permitAll()
                        .anyRequest()
                        .authenticated())
                .httpBasic(Customizer.withDefaults())
                .build();
    }

}

Understanding Every Line of Code

@Configuration

Marks this class as a Spring configuration class.

Spring Boot scans this class and creates beans from it.

@EnableWebSecurity

Enables Spring Security support.

It activates the internal security filter chain.

SecurityFilterChain

This bean defines how requests should be secured.

Every request entering the application passes through a chain of security filters before reaching the controller.

CSRF Configuration

.csrf(AbstractHttpConfigurer::disable)

Cross-Site Request Forgery protection is generally disabled for REST APIs because APIs are stateless.

In browser-based applications, CSRF protection should usually remain enabled.

requestMatchers()

.requestMatchers("/api/public")
.permitAll()

This means:

Anyone can access:

GET /api/public

No authentication is required.

authenticated()

.anyRequest()
.authenticated()

All remaining APIs require authentication.

Therefore:

Endpoint

Access

/api/public

Public

/api/private

Authentication Required


HTTP Basic Authentication

.httpBasic(Customizer.withDefaults())

Spring Security enables Basic Authentication.

Credentials are sent inside the Authorization header.

Example:

Authorization: Basic dXNlcjpwYXNzd29yZA==

Basic Authentication is useful for learning and internal services, but most production systems use JWT authentication.

Default User Generated by Spring Boot

When Spring Security is added, Spring Boot automatically creates a default user.

Username:

user

Password:

Generated at application startup.

Example:

Using generated security password:
13d2b6a7-fc80-40df-a215-2c7b3ce8e6cb

The password appears in the console logs.

Testing APIs

Public Endpoint

Request:

GET /api/public

Response:

Public API

Authentication is not required.

Private Endpoint

Request:

GET /api/private

Without credentials:

401 Unauthorized

With credentials:

Private API

How Spring Security Works Internally

Request flow:

Client
   ↓
Security Filter Chain
   ↓
Authentication FilterAuthorization Filter
   ↓
Controller
   ↓
Response

Spring Security intercepts every request before it reaches business logic.

This architecture makes applications secure and highly extensible.

Real-World Example

Suppose we are building an Online Banking Application.

Public APIs:

/api/auth/login
/api/auth/register
/api/auth/forgot-password

Protected APIs:

/api/accounts
/api/transactions
/api/payments
/api/profile

Only authenticated customers should access account and transaction information.

Spring Security provides the infrastructure required to enforce these rules.


Production-Level Best Practices

Never Make Everything Public

Avoid:

.anyRequest().permitAll()

because it exposes every API.

Use HTTPS

Credentials and tokens should always travel over encrypted connections.

Store Passwords Securely

Never store plain-text passwords.

Use:

BCryptPasswordEncoder

for password hashing.

Prefer JWT Authentication

Basic Authentication is suitable for learning purposes.

Production applications generally use:

  • JWT

  • OAuth2

  • OpenID Connect

because they are stateless and scalable.

Separate Security from Business Logic

Keep authentication and authorization inside dedicated configuration classes.

Controllers should focus only on business functionality.

Summary

In this article, we learned:

  • What Spring Security 7 is.

  • Why security is essential.

  • Adding Spring Security to a Spring Boot 4 application.

  • Creating a REST API.

  • Configuring SecurityFilterChain.

  • Understanding request authorization.

  • Using HTTP Basic Authentication.

  • Internal working of Spring Security.

  • Production-level recommendations.

In Part 2, we will explore Authentication and Authorization in depth and learn how users, roles, and permissions work inside Spring Security 7.

Enjoyed this article?

Subscribe to our newsletter for more backend engineering insights and tutorials.