How do you handle JWT authentication in Spring Boot?

Table of Contents

Introduction

JSON Web Tokens (JWT) have become a standard method for securing REST APIs and handling authentication in modern web applications. In Spring Boot applications, JWT is often used for stateless authentication, where a token is issued upon user login, and subsequent API requests are authenticated using this token.

In this guide, we'll show you how to implement JWT authentication in Spring Boot using Spring Security. We'll cover the steps to:

  1. Generate JWT tokens after a successful login.
  2. Validate JWT tokens for protected API endpoints.
  3. Secure REST APIs using JWT-based authentication.

1. Set Up Dependencies

To start, you need to add the necessary dependencies for Spring Boot and JWT in your pom.xml (for Maven) or build.gradle (for Gradle).

Maven Dependencies:

Gradle Dependencies:

2. Create a JWT Utility Class

The first step in implementing JWT authentication is creating a utility class for generating and validating JWT tokens. This class will use the jjwt library to handle token creation and parsing.

Example: JwtUtil Class

Explanation:

  • **generateToken()**: Creates a JWT token, including the username and an expiration time (10 hours).
  • **extractUsername()**: Extracts the username (subject) from the token.
  • **extractClaims()**: Extracts all claims from the JWT token.
  • **validateToken()**: Validates if the token is valid by checking if the username matches and the token is not expired.
  • **isTokenExpired()**: Checks if the JWT token has expired.

3. Create an Authentication Filter

Next, we need an authentication filter that will intercept incoming requests, extract the JWT token from the Authorization header, validate it, and authenticate the user if the token is valid.

Example: JwtAuthenticationFilter

Explanation:

  • The filter looks for the Authorization header in the request, checks if it contains a valid JWT token, and extracts the username from the token.
  • If the token is valid, it creates an Authentication object and sets it in the SecurityContext.

4. Create a Controller to Handle Login

For the login process, you'll need to create a controller that accepts the user's credentials, authenticates them, and returns a JWT token upon successful login.

Example: AuthController

Explanation:

  • The /auth/login endpoint accepts username and password as request parameters.
  • The authenticationManager.authenticate() method checks if the user credentials are valid.
  • Upon successful authentication, a JWT token is generated and returned.

5. Configure Spring Security

In Spring Security, we need to configure the HTTP security to allow the JWT filter and secure the REST API endpoints. Specifically, we need to add the JwtAuthenticationFilter and configure access control.

Example: SecurityConfig

Explanation:

  • The /auth/login endpoint is explicitly allowed without authentication.
  • All other endpoints require a valid JWT token for access.
  • The JWT filter (JwtAuthenticationFilter) is added before the security filter chain.

6. Securing API Endpoints with JWT

Now that the authentication process is set up, you can secure your API endpoints using JWT-based authentication. All you need to do is apply appropriate annotations to your endpoints.

Example: Securing REST API Endpoint

Explanation:

  • The /hello endpoint is protected by Spring Security. A valid JWT token is required to access it.

Conclusion

In this guide, we have implemented JWT authentication in Spring Boot using Spring Security. We:

  • Created a JWT utility class for token generation and validation.
  • Implemented a JWT authentication filter to intercept requests and authenticate users.
  • Set up a controller for user login that returns a JWT token.
  • Configured Spring Security to secure API endpoints using JWT.

This approach allows for stateless authentication, where the server does not need to store session information. Instead, the token is passed with each request, ensuring a scalable and efficient security model.

Similar Questions