Learn Spring Boot Β· 9/14

Advanced Security: Stateless APIs and JWT

10 min read

Advanced Security: Stateless APIs and JWT

Welcome back! Today, we're diving deep into a crucial topic for modern web applications: securing our APIs in a stateless manner. This might sound a bit technical, but don't worry, we'll break it down step-by-step.

At its core, we're trying to solve a fundamental problem: how does our server know who is making a request, and what they are allowed to do, without having to remember them from previous interactions? This is especially important in today's world of microservices and distributed systems.


1. The Shift to Stateless: Why JWT (JSON Web Tokens)?

What's the "State" in Stateless? πŸ€”

Imagine you're a barista at a busy coffee shop. In a stateful world, you'd have to remember every single customer's order. "Hi, I'll have the usual." would work perfectly. But what if there are thousands of customers and multiple baristas? It quickly becomes a nightmare to keep track of everyone.

This is similar to how traditional web applications worked with sessions. The server would store information about a logged-in user and give them a session ID. With every request, the server would look up this session information. This works, but it has its challenges, especially when you have many servers (scaling is difficult).

Now, imagine a stateless coffee shop. Every time a customer orders, they present a special token that has their entire order written on it: "One large latte with oat milk for John Doe." The barista doesn't need to remember anything; they just look at the token, make the coffee, and hand it over.

This is the essence of stateless authentication. The server doesn't need to store any session information. All the necessary information is contained within a token that the client sends with each request. This makes our application much easier to scale and manage, especially in a microservices architecture.

So, What is a JWT? 🎟️

A JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. Think of it as that special coffee shop token. It's a string of characters that looks like gibberish at first, but it's actually composed of three parts separated by dots (.).

xxxxx.yyyyy.zzzzz

Let's break it down:

  • Header: This part usually contains two pieces of information: the type of token (which is JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.
  • Payload: This is where the actual data, or "claims," are stored. Claims are statements about an entity (typically, the user) and additional data. There are registered claims (like iss for issuer, exp for expiration time, and sub for subject) and you can also include your own custom claims (like user roles).
  • Signature: This is the part that ensures the token's integrity. To create the signature, you take the encoded header, the encoded payload, a secret key, and run it through the algorithm specified in the header. This signature verifies that the sender of the JWT is who it says it is and ensures that the message wasn't changed along the way.

Interesting Fact: A common misconception is that JWTs are encrypted. By default, they are only Base64Url encoded, which means anyone can read the payload if they intercept the token! The security of a JWT comes from its signature, which prevents tampering. If you need to include sensitive information, the JWT can be encrypted to form a JSON Web Encryption (JWE) token.


2. Token Mechanics: Generating, Signing, and Validating JWTs

Now for the fun part: let's see how we can actually create and work with these tokens in a Spring Boot application.

Getting Set Up πŸ› οΈ

First things first, you'll need to add the necessary dependencies to your pom.xml to work with JWTs. A popular and robust library for this in the Java world is jjwt.

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>

Generating a JWT πŸͺ„

Let's create a simple service to handle JWT operations. The core of this service will be a method to generate a token.

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

import java.util.Date;

@Service
public class JwtUtil {

    private final String SECRET_KEY = "your-super-secret-key-that-is-long-and-secure";

    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10 hours
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }
}

In this snippet, we're using the Jwts builder from the jjwt library to construct our token. We set the subject (the username), the issue date, and an expiration date. Finally, we sign it with the HS256 algorithm and our secret key.

Industry Practice: Never hardcode your secret key directly in the code. It's much better to store it in your application's configuration file (application.properties or application.yml) and access it through Spring's @Value annotation. For production environments, consider even more secure options like environment variables or a dedicated secrets management tool. A strong secret key should be at least 256 bits of random data.

Signing Algorithms: A Quick Detour πŸš—

There are two main families of algorithms for signing JWTs:

  • Symmetric (HMAC): Like HS256, these algorithms use the same secret key to both sign and verify the token. This is simpler to set up but means that any service that needs to validate the token must also have access to the secret key.
  • Asymmetric (RSA, ECDSA): These use a public/private key pair. The token is signed with the private key, and it can be verified by anyone who has the public key. This is generally more secure, especially in a microservices architecture where you might have multiple services that need to validate tokens but shouldn't have the power to create them.

Validating a JWT βœ…

Of course, generating a token is only half the story. We also need to be able to validate it when it comes back in a request.

java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

// ... inside JwtUtil class

public Boolean validateToken(String token, String username) {
    final String extractedUsername = extractUsername(token);
    return (extractedUsername.equals(username) && !isTokenExpired(token));
}

public String extractUsername(String token) {
    return extractClaim(token, Claims::getSubject);
}

public Date extractExpiration(String token) {
    return extractClaim(token, Claims::getExpiration);
}

public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
    final Claims claims = extractAllClaims(token);
    return claimsResolver.apply(claims);
}

private Claims extractAllClaims(String token) {
    return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}

private Boolean isTokenExpired(String token) {
    return extractExpiration(token).before(new Date());
}

The extractAllClaims method is the heart of the validation process. It uses the same secret key to parse the token. If the signature is invalid or the token has been tampered with, this method will throw an exception. We then have helper methods to extract specific claims like the username and expiration date. It's crucial to always check for token expiration.


3. Creating a Custom JWT Authentication Filter

Now that we have the mechanics for handling JWTs, we need to integrate this into Spring Security's filter chain. This will allow us to intercept incoming requests, check for a valid JWT, and set up the security context if one is found.

The OncePerRequestFilter πŸšͺ

Spring Security is built around a chain of filters that process incoming requests. To add our JWT validation logic, we'll create a custom filter that extends OncePerRequestFilter. This ensures our filter is executed only once for each request.

java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}

Here's what this filter does:

  1. It checks the Authorization header for a Bearer token.
  2. If a token is found, it extracts the username from it.
  3. If a username is extracted and there's no existing authentication in the SecurityContextHolder, it loads the user's details.
  4. It then validates the token.
  5. If the token is valid, it creates a UsernamePasswordAuthenticationToken and sets it in the SecurityContextHolder. This is how we tell Spring Security that the current user is authenticated.

Configuring Spring Security to Use Our Filter βš™οΈ

The final piece of the puzzle is to tell Spring Security to use our custom filter and to make our authentication stateless.

java
import org.springframework.beans.factory.annotation.Autowired;
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.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeHttpRequests((authz) -> authz
                .requestMatchers("/authenticate").permitAll()
                .anyRequest().authenticated()
            )
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

The key parts here are:

  • sessionCreationPolicy(SessionCreationPolicy.STATELESS): This tells Spring Security not to create or use any sessions, making our application truly stateless.
  • addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class): This adds our custom filter to the filter chain before the default UsernamePasswordAuthenticationFilter.

4. Role-Based Access Control (RBAC): Using @PreAuthorize and Roles

Just knowing who a user is (authentication) is often not enough. We also need to know what they are allowed to do (authorization). This is where Role-Based Access Control (RBAC) comes into play.

Adding Roles to the JWT 🎭

The first step is to include the user's roles as a custom claim in the JWT payload when we generate it.

java
// In your JWT generation logic
// Assuming you have a UserDetails object with authorities (roles)
.claim("roles", userDetails.getAuthorities().stream()
        .map(GrantedAuthority::getAuthority)
        .collect(Collectors.toList()))

Now, the generated token will contain information about the user's roles.

Enabling Method-Level Security πŸ”’

To use annotations like @PreAuthorize, we need to enable global method security in our security configuration.

java
// Add this annotation to your SecurityConfig class
@EnableGlobalMethodSecurity(prePostEnabled = true)

This annotation enables Spring Security's pre- and post-authorization checks.

Protecting Endpoints with @PreAuthorize πŸ›‘οΈ

With method-level security enabled, we can now protect our controller methods with the @PreAuthorize annotation. This annotation takes a Spring Expression Language (SpEL) expression as an argument to determine if the method should be executed.

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("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String adminEndpoint() {
        return "Hello, Admin!";
    }

    @GetMapping("/user")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public String userEndpoint() {
        return "Hello, User!";
    }
}

In this example:

  • The /admin endpoint can only be accessed by users with the ADMIN role.
  • The /user endpoint can be accessed by users with either the USER or ADMIN role.

If an unauthorized user tries to access these endpoints, Spring Security will automatically return a 403 Forbidden status.

A Funny Exaggeration: Think of @PreAuthorize as a very picky bouncer at a club. They're not just checking if you have an ID (authentication); they're checking if your name is on the VIP list, if you're wearing the right shoes, and if you know the secret handshake (authorization).


Further Reading πŸ“š

Challenge

You are tasked with creating a JWT utility class in a Spring Boot application. This class, JwtUtil, will be responsible for generating, validating, and extracting information from JSON Web Tokens using the jjwt library.

Complete the implementation of the JwtUtil class in Java. You must fill in the logic for the following three key methods based on the provided class structure:

  1. generateToken(UserDetails userDetails):

    • Create a map for custom claims. Extract the user's authorities, convert them to a list of strings, and add this list to the map with the key "roles".
    • Build the JWT by setting the custom claims, the subject (as the username), the "issued at" timestamp (current time), and an expiration timestamp 10 hours from now.
    • Sign the token using the HS256 algorithm and the provided SECRET_KEY.
    • Return the compact JWT string.
  2. extractAllClaims(String token):

    • This is a private helper method. It should parse the incoming token string using the SECRET_KEY to verify the signature and return the Claims object.
  3. validateToken(String token, UserDetails userDetails):

    • Extract the username from the token.
    • Verify that the extracted username matches the username from the userDetails object.
    • Verify that the token has not expired.
    • The method must return true only if both the username matches and the token is not expired.

Expected result

Your completed JwtUtil class should correctly use the jjwt library to handle all JWT operations. The final code should replace the TODO sections and placeholders with a full implementation.

Key Implementation Points:

  • extractAllClaims(String token): This method must be implemented using Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody() to parse the token and return the Claims object.

  • generateToken(UserDetails userDetails):

    • This method should first create a Map<String, Object> claims.
    • It must correctly populate the map with a "roles" key, where the value is a list of authority strings derived from userDetails.getAuthorities().
    • It should use Jwts.builder() to chain method calls: setClaims(claims), setSubject(userDetails.getUsername()), setIssuedAt(new Date(System.currentTimeMillis())), and setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)).
    • The chain must end with .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact() to produce the final token string.
  • validateToken(String token, UserDetails userDetails):

    • It should declare a final variable username by calling extractUsername(token).
    • It must return the result of a boolean expression that checks two conditions: username.equals(userDetails.getUsername()) AND !isTokenExpired(token).
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.