Learn Spring · 8/15

Securing Your Application with Spring Security

10 min read

Securing Your Application with Spring Security 🛡️

Welcome, fearless developer, to the world of Spring Security! Don't be intimidated by the seemingly complex world of application security. We're going to break it down into easy-to-understand concepts, just like learning your ABCs before writing a novel. Our goal is to equip you with the most frequently used, industry-standard practices to protect your applications from unwanted intruders.

1. Spring Security Basics: Authentication vs Authorization

Let's start at the very beginning. In the realm of security, two words pop up constantly: Authentication and Authorization. They sound similar, but they do very different jobs.

The Problem: Imagine you have a super-secret diary application. You want to make sure that only you can log in and that once you're in, you can only write in your own diary, not someone else's. How do you control who gets in and what they can do?

This is where Authentication and Authorization come to the rescue.

Authentication (Who are you? 🤔):

Authentication is all about verifying identity. It's the process of making sure someone is who they claim to be. Think of it as the bouncer at a club checking your ID. Before they let you in, they need to confirm you are the person on the ID.

In the world of web applications, this is typically done with a username and password. The user provides their credentials, and your application checks if they match what's stored in your system.

Authorization (What are you allowed to do? 🔑):

Once a user is authenticated (they're inside the club), authorization determines what they are allowed to do. Can they access the VIP lounge? Can they order from the secret menu?

In our diary application, after you've successfully logged in (authenticated), authorization would check if you're trying to access your own diary or someone else's. You are authorized to read and write in your own diary, but not in anyone else's.

Here's a simple breakdown:

Concept Question it Answers Real-world Analogy Technical Example
Authentication "Who are you?" Showing your ID to enter a building. Logging in with a username and password.
Authorization "What can you do?" Your keycard only opening specific doors in the building. A user being able to view their own profile but not the admin dashboard.

It's a two-step process: First, you prove who you are (Authentication). Then, the system checks what you have permission to do (Authorization). You can't be authorized without first being authenticated.


2. Securing Endpoints: Configuring the SecurityFilterChain

Alright, now that we understand the "who" and the "what," let's put it into practice. How do we tell our Spring application which parts need protection?

The Problem: Your application has several endpoints (URLs). Some, like the homepage or a product listing, should be public. Others, like a user's account page or an admin panel, must be protected. You need a centralized way to define these security rules.

The Solution: SecurityFilterChain

In modern Spring Security, you configure your security rules by creating a SecurityFilterChain bean. Think of this as a set of rules that Spring Security will apply to incoming requests. It's like setting up a series of checkpoints for every request that comes into your application.

Getting Started:

First, you need the Spring Security dependency in your pom.xml (for Maven) or build.gradle (for Gradle).

Maven (pom.xml):

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

Configuration (SecurityConfig.java):

Here’s a basic configuration to get us started. We'll create a class and annotate it with @Configuration and @EnableWebSecurity.

java
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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorizeRequests ->
                authorizeRequests
                    .requestMatchers("/api/public/**").permitAll() // Anyone can access this
                    .requestMatchers("/api/user/**").hasRole("USER") // Only users with the "USER" role
                    .requestMatchers("/api/admin/**").hasRole("ADMIN") // Only users with the "ADMIN" role
                    .anyRequest().authenticated() // All other requests need authentication
            )
            .formLogin(); // Provides a default login form
        return http.build();
    }
}

Under the Hood:

When a request comes in, Spring Security runs it through this chain of rules. It checks the URL and sees which requestMatchers it matches first. The order matters! It's generally a good practice to go from most specific to most general rules.

  • requestMatchers("/api/public/**").permitAll(): This says any URL starting with /api/public/ is open to everyone. No login required.
  • requestMatchers("/api/user/**").hasRole("USER"): To access anything under /api/user/, you must be logged in and have the 'USER' role.
  • requestMatchers("/api/admin/**").hasRole("ADMIN"): To get into the admin section, you need the 'ADMIN' role.
  • anyRequest().authenticated(): This is a catch-all. Any other request that doesn't match the rules above requires the user to be authenticated.
  • .formLogin(): This is a handy helper that tells Spring Security to generate a default login page. No need to build one from scratch just to get started!

This centralized configuration is powerful because it keeps all your security rules in one place, making them easier to manage and reason about.


3. Managing Users: Implementing UserDetailsService and Password Encoding

Spring Security now knows what to protect, but it doesn't know anything about our users yet.

The Problem: Where do our users' usernames, passwords, and roles come from? Are they in a database? In memory? How do we securely store their passwords? (Hint: Never, ever, ever store passwords in plain text!).

The Solution: UserDetailsService and PasswordEncoder

UserDetailsService is an interface in Spring Security with a single mission: to load user-specific data. You implement this interface to tell Spring Security how to find your users.

PasswordEncoder is another interface that deals with... you guessed it, encoding passwords. We use it to hash passwords before saving them and to compare a submitted password with the stored hash during login.

Implementing UserDetailsService:

Let's imagine we have a User entity and a UserRepository to fetch users from a database.

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 JpaUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

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

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userRepository.findByUsername(username)
                .map(SecurityUser::new) // Assuming you have a SecurityUser class that implements UserDetails
                .orElseThrow(() -> new UsernameNotFoundException("Username not found: " + username));
    }
}

In this example, when a user tries to log in, Spring Security will call our loadUserByUsername method with the provided username. Our code then looks up the user in the database. If found, it returns a UserDetails object containing the username, password (hashed!), and authorities (roles).

Password Encoding:

Now for the crucial part: never store passwords as plain text. We need to hash them. A popular and secure hashing algorithm is bcrypt.

First, we need to create a PasswordEncoder bean in our SecurityConfig.

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

// Inside your SecurityConfig class
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

By declaring this bean, Spring Security will automatically pick it up and use it to compare the submitted password with the stored hashed password.

When creating a new user, you would use this encoder to hash the password before saving it:

java
// In your user creation service
@Autowired
private PasswordEncoder passwordEncoder;

public void createUser(String username, String rawPassword) {
    User newUser = new User();
    newUser.setUsername(username);
    newUser.setPassword(passwordEncoder.encode(rawPassword));
    // ... set roles and save the user
    userRepository.save(newUser);
}

Fun Fact: BCrypt is designed to be slow on purpose! This makes it much harder for attackers to try many passwords in a short amount of time (a "brute-force" attack).


4. Stateless Security: Generating and Validating JWT (JSON Web Tokens)

So far, we've been dealing with traditional session-based authentication (thanks to .formLogin()). This works well for many applications. But what if you have a modern single-page application (like React or Angular) or a mobile app talking to your backend? Or what if you have multiple microservices that need to trust each other?

The Problem: In a distributed system, managing sessions on the server can become a headache. Each server needs to know about the user's session. This is "stateful" because the server has to remember the state of the user's login. We want to be "stateless."

The Solution: JSON Web Tokens (JWT)

JWT is a compact, URL-safe means of representing claims to be transferred between two parties. In simpler terms, it's a secure string of text that contains information about the user (like their username and roles).

Here's the flow:

  1. A user logs in with their username and password.
  2. The server validates the credentials.
  3. If they are correct, the server generates a JWT and sends it back to the client.
  4. The client then includes this JWT in the Authorization header of every subsequent request (usually as Bearer <token>).
  5. The server validates the JWT on each request to know who the user is and what they can do.

The server doesn't have to store anything about the user's session. All the necessary information is in the token!

Generating a JWT:

You'll need a library to help with JWTs. A popular one is jjwt.

Maven (pom.xml):

xml
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.5</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.11.5</version>
    <scope>runtime</scope>
</dependency>

Here's a simplified example of a service to generate a token:

java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;

@Service
public class JwtTokenProvider {

    private final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); // A secure key

    public String generateToken(String username) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + 86400000); // 1 day expiration

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(key)
                .compact();
    }

    // You'll also need a method to validate the token and get the username from it
}

Configuring Spring Security for JWT:

To use JWTs, you need to tell Spring Security to stop creating sessions and to add a filter that checks for the JWT on each request.

java
// Inside your SecurityFilterChain configuration
import org.springframework.security.config.http.SessionCreationPolicy;

// ...
http
    // ... other configurations
    .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

// You would also add a custom filter to process the JWT
// http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

This tells Spring Security, "Don't bother creating HttpSession objects; we're going stateless!"


5. Role-Based Access Control (RBAC): Fine-grained Security with @PreAuthorize

We've secured our URLs, but what if we need more granular control? What if a method within a controller should only be accessible by an admin?

The Problem: Sometimes, securing entire URL patterns isn't enough. You might have a single endpoint, say GET /api/users/{id}, that should behave differently based on the user's role. A regular user should only be able to get their own data, but an admin should be able to get anyone's data.

The Solution: Method-level Security with @PreAuthorize

Spring Security allows you to add security checks directly on your methods. To enable this, you need to add an annotation to your configuration:

java
// In your SecurityConfig
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    // ... your beans
}

Now, you can use annotations like @PreAuthorize on your controller methods or service layer methods.

java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/api/data/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String getAdminData() {
        return "This is top secret admin data!";
    }

    @GetMapping("/api/data/user")
    @PreAuthorize("hasRole('USER')")
    public String getUserData() {
        return "Some regular user data.";
    }

    @GetMapping("/api/users/{username}")
    @PreAuthorize("#username == authentication.name or hasRole('ADMIN')")
    public String getUserProfile(String username) {
        // A user can see their own profile, or an admin can see any profile
        return "Profile data for " + username;
    }
}

How it Works:

@PreAuthorize uses Spring Expression Language (SpEL) to define its rules. This is incredibly powerful!

  • hasRole('ADMIN'): Checks if the current authenticated user has the 'ADMIN' role.
  • #username == authentication.name: This is where it gets really cool. You can access method arguments (#username) and information about the current authentication (authentication.name gives you the username of the logged-in user).

This allows for very fine-grained and expressive security rules right where the logic is, making your code easier to read and secure.


References for Extra Reading 📚

  • Spring Security Documentation: The official source of truth. Always a good place to start.
  • Baeldung's Spring Security Tutorials: A fantastic resource with lots of practical examples.
  • JWT Introduction: A great place to learn more about the structure and use cases for JSON Web Tokens.

Challenge

Challenge: Configure a Stateless Security Filter Chain

Your task is to implement a SecurityFilterChain bean within the provided SecurityConfig class. You must configure the application's security rules according to the following requirements for a modern, stateless API:

  1. CSRF Protection: Disable Cross-Site Request Forgery (CSRF) protection.
  2. Endpoint Authorization: Configure the following URL-based authorization rules. Remember that more specific rules should be declared before more general ones.
    • Any request to /api/v1/admin/** must require the ADMIN role.
    • Any request to /api/v1/users/{username}/** must require either the ADMIN role OR the USER role.
    • Requests to /auth/** and /products/public/** must be permitted for all users, including unauthenticated ones.
    • All other requests not matching the patterns above must be authenticated.
  3. Session Management: Configure the session management policy to be STATELESS, as this API will rely on tokens for authentication instead of sessions.
  4. Authentication Mechanism: Enable HTTP Basic authentication as a placeholder authentication method.

Expected result

Your code should be a complete implementation of the filterChain method. The method should construct and return a SecurityFilterChain object built from the HttpSecurity parameter.

The final implementation should use a chained method call structure on the http object. It must correctly configure:

  • CSRF to be disabled using .csrf(csrf -> csrf.disable()).
  • Authorization rules within an .authorizeHttpRequests() block, containing specific requestMatchers for each path (/api/v1/admin/**, /api/v1/users/{username}/**, /auth/**, /products/public/**) with their corresponding access control methods (hasRole(), hasAnyRole(), permitAll()), and a final .anyRequest().authenticated().
  • Session management policy set to stateless: .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).
  • HTTP Basic authentication enabled with .httpBasic().
  • The chain must end with a .build() call.
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.