Spring Security Essentials: Locking the Front Door

8 min read

Securing a web application can feel intimidating. One wrong move, and your application's data is exposed to the world. However, Spring Security is an incredibly robust, battle-tested framework designed to handle the heavy lifting of keeping the bad actors out while letting the right people in.

In this guide, we will break down the essential concepts of Spring Security, moving progressively from the absolute basics to configuring an industry-standard, database-backed authentication system. Let's lock the front door! 🔒


1. Authentication vs. Authorization: Concepts Explained

Before we write a single line of code, we must understand the two foundational pillars of application security.

Definition:

  • Authentication is the process of verifying the identity of a user or system.
  • Authorization is the process of determining whether an authenticated user has permission to perform a specific action or access a specific resource.

The Problem:
When an HTTP request arrives at your server, it is completely stateless and anonymous. The server has absolutely no idea who is making the request. If you do not solve this, any anonymous user on the internet can trigger actions like deleting your database or viewing sensitive customer data.

The Solution:
We enforce Authentication to force the requester to prove who they are (usually by providing a valid username and password, or a secure token). Once we know exactly who they are, we enforce Authorization to check their assigned roles (like USER or ADMIN) against the rules of the resource they are trying to access.

Real-Life Scenario Flow

Imagine you are running a pizza shop (the server). You have customers (requests) coming in constantly.

  1. A person walks into the shop and asks to enter the Employee-Only kitchen. You ask to see their employee badge. They show you a badge with their photo and name. This is Authentication. You have successfully verified they are who they claim to be.
  2. Now that you know who they are, you check their job title. It turns out they are a delivery driver, not a chef. You deny them entry to the kitchen. This is Authorization. You verified their permissions based on their established identity.

Fun Fact: If you mix these two concepts up in your code, you might successfully prove someone is a malicious hacker (Authentication), and then politely grant them permission to drop your production database tables (Authorization). Let's avoid that! 😅


2. Adding Spring Security: Understanding Default Auto-Configuration Behavior

Definition:
Spring Security Auto-Configuration is a feature of Spring Boot that automatically applies a default, highly restrictive set of security rules to your application the moment the Spring Security dependency is detected on the classpath.

The Problem:
Configuring web security from scratch is risky and tedious. You have to write boilerplate code to intercept requests, handle session fixation attacks, mitigate Cross-Site Request Forgery (CSRF), and securely hash passwords. Doing this manually leaves room for human error.

The Solution:
Spring Boot provides a "secure-by-default" environment. By simply adding the dependency, Spring Boot assumes you want everything locked down immediately until you explicitly state otherwise.

Installation / Setup

To get started in a Spring Boot 3.x application, simply add the starter dependency to your pom.xml:

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

What happens under the hood?

The moment you start your application with this dependency, Spring Boot does a few things automatically:

  1. Locks Everything: Every single HTTP endpoint in your application now requires authentication.
  2. Generates a User: It creates an in-memory user with the username user.
  3. Generates a Password: It prints a randomly generated UUID password to your console log upon startup (e.g., Using generated security password: 9b12a8...).
  4. Generates Forms: It provides a default HTML login page and a default logout page.

Printing passwords to the console is great for a quick 5-minute prototype, but in the real world, you do not want to rely on auto-generated console passwords. We need to take control of this behavior.


3. Customizing the SecurityFilterChain: Who Gets Access to What?

Definition:
The SecurityFilterChain is an interface that represents a chain of standard Servlet Filters. Spring Security uses this chain to intercept incoming HTTP requests and apply authentication and authorization logic before the request ever reaches your application's Controllers.

The Problem:
The default auto-configuration locks everything. In a real-world application, this is rarely what you want. You need public endpoints (like a /register page or a homepage) to be accessible to anyone, while restricting private endpoints (like /dashboard) to logged-in users, and highly sensitive endpoints (like /admin-panel) to administrators.

The Solution:
You override the default behavior by defining a custom SecurityFilterChain Bean. This tells Spring Security exactly which URLs should be public, which require authentication, and which require specific roles.

Real-Life Scenario Flow

Imagine your pizza shop again. When a customer walks through the front door, they enter the dining area.

  • Public Access: Anyone can walk into the dining area and look at the menu without showing an ID.
  • Authenticated Access: Only people who have paid (authenticated) can go to the buffet table.
  • Authorized Access: Only the MANAGER can open the cash register.
    The SecurityFilterChain is the set of rules the security guard uses to manage this traffic.

Writing the Code (Spring Security 6.x Standard)

In Spring Security 6.x, the old WebSecurityConfigurerAdapter has been completely removed. Instead, we use a component-based approach by declaring a SecurityFilterChain bean and utilizing a Lambda DSL (Domain Specific Language) for configuration.

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 1. Disable CSRF if you are building stateless REST APIs (like with React/Angular)
            // If you are using Spring MVC with Thymeleaf/JSP, leave CSRF enabled!
            .csrf(csrf -> csrf.disable()) 
            
            // 2. Configure HTTP request authorization rules
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**", "/register").permitAll() // Anyone can access
                .requestMatchers("/admin/**").hasRole("ADMIN")          // Only ADMIN role
                .anyRequest().authenticated()                           // All other requests require login
            )
            
            // 3. Define the authentication mechanism
            .formLogin(Customizer.withDefaults()) // Use default Spring HTML login form
            .httpBasic(Customizer.withDefaults()); // Support Basic Auth (Postman/API calls)

        return http.build();
    }
}

What happens under the hood?
When an HTTP request arrives, the Servlet Container passes it to a proxy class called DelegatingFilterProxy. This proxy hands the request over to Spring Security's FilterChainProxy. The proxy looks at your SecurityFilterChain Bean, evaluates the URL paths step-by-step from top to bottom, and applies your security rules.


4. User Management: Moving from In-Memory to Database-Backed Users

Definition:
UserDetailsService is a core Spring Security interface with a single method used to retrieve user authentication and authorization data. UserDetails is the interface representing the user model that Spring Security understands.

The Problem:
By default, Spring Boot creates a single in-memory user. When the server restarts, that user's data vanishes. You cannot run an industry-standard application without persistently storing multiple users, their hashed passwords, and their roles in a database.

The Solution:
We map our database table to a Spring Data JPA Entity, and then create a custom implementation of the UserDetailsService. When a user attempts to log in, Spring Security calls our custom service, queries the database, and converts our database record into a UserDetails object.

Industry Standard: Password Hashing

Never, ever store passwords in plain text in your database. If your database is compromised, all user passwords are leaked. We use a PasswordEncoder (specifically BCryptPasswordEncoder) to securely hash passwords.

Step-by-Step Implementation

Step 1: Define the PasswordEncoder Bean

Add this to your SecurityConfig class so Spring knows how to verify hashes.

java
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

Step 2: Create the User Entity

This represents your database table.

java
import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class UserEntity {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(unique = true, nullable = false)
    private String username;
    
    @Column(nullable = false)
    private String password; // This will store the BCrypt hash
    
    @Column(nullable = false)
    private String role; // e.g., "ROLE_USER" or "ROLE_ADMIN"

    // Getters and Setters omitted for brevity
    public String getUsername() { return username; }
    public String getPassword() { return password; }
    public String getRole() { return role; }
}

Step 3: Create the Repository

A standard Spring Data JPA repository to fetch the user by their username.

java
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;

public interface UserRepository extends JpaRepository<UserEntity, Long> {
    Optional<UserEntity> findByUsername(String username);
}

Step 4: Implement CustomUserDetailsService

This is the bridge between your database and Spring Security. Spring Security will automatically detect this Bean and use it for the login process.

java
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.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    // Constructor Injection
    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. Fetch user from the database
        UserEntity userEntity = userRepository.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));

        // 2. Map your UserEntity to Spring Security's internal User object
        return User.builder()
            .username(userEntity.getUsername())
            .password(userEntity.getPassword()) // Spring will check this hash against the provided password
            .authorities(userEntity.getRole())  // Assign roles for Authorization
            .build();
    }
}

How the Flow Connects

  1. A user submits a username and password to /login.
  2. Spring Security calls CustomUserDetailsService.loadUserByUsername().
  3. Your code queries the database and returns a UserDetails object containing the hashed password.
  4. Spring Security takes the plain-text password the user just typed, hashes it using your PasswordEncoder, and compares it to the hash from the database.
  5. If they match, the user is Authenticated. Spring then checks the .authorities() to see if they are Authorized to access their requested URL.

You have successfully locked the front door and handed keys only to the people who belong in the building! 🏢


References & Further Reading

Challenge

Your goal is to configure Spring Security to use a database-backed user store for authentication. You are provided with a UserEntity class, which represents a user record from a database, and a UserRepository interface for data access.

In the provided SecurityConfig class, you must implement and expose two critical beans:

  1. PasswordEncoder Bean: Create a bean that provides an instance of BCryptPasswordEncoder. This is the standard for securely hashing and verifying passwords.

  2. UserDetailsService Bean: Create a bean that implements the UserDetailsService interface. This service acts as the bridge between your user data store (UserRepository) and Spring Security.

    • This service's primary method receives a username.
    • Use the injected userRepository to look up the UserEntity for that username.
    • If the UserEntity is not found, you must throw a UsernameNotFoundException.
    • If found, you must transform the UserEntity into an object that implements UserDetails (e.g., org.springframework.security.core.userdetails.User). This object must contain the username, the hashed password from the database, and a collection of GrantedAuthority.
    • The role from UserEntity (e.g., "ADMIN") must be converted into a GrantedAuthority with the prefix "ROLE_" (e.g., "ROLE_ADMIN").

Expected result

Your SecurityConfig class should be fully implemented with two essential beans defined using the @Bean annotation: passwordEncoder and userDetailsService.

The passwordEncoder bean method should simply return a new instance of BCryptPasswordEncoder.

The userDetailsService bean method should return a lambda implementation of UserDetailsService. This lambda will use the injected UserRepository to fetch user data. It will check if the user entity exists, throwing a UsernameNotFoundException if it doesn't. If the user exists, it will construct and return a org.springframework.security.core.userdetails.User object, correctly mapping the username, hashed password, and role (converted to a SimpleGrantedAuthority with the "ROLE_" prefix).

Here is a complete example of the expected implementation:

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Collections;

// --- Assume these classes are provided and cannot be modified ---
class UserEntity {
    private String username;
    private String password;
    private String role;
    public UserEntity(String username, String password, String role) { this.username = username; this.password = password; this.role = role; }
    public String getUsername() { return username; }
    public String getPassword() { return password; }
    public String getRole() { return role; }
}
interface UserRepository {
    UserEntity findByUsername(String username);
}
// --- End of provided classes ---

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final UserRepository userRepository;

    public SecurityConfig(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            UserEntity userEntity = userRepository.findByUsername(username);
            if (userEntity == null) {
                throw new UsernameNotFoundException("User not found: " + username);
            }
            return new User(
                userEntity.getUsername(),
                userEntity.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + userEntity.getRole()))
            );
        };
    }
}
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.