JWT Implementation with Spring Boot 3 and Spring Security 6

Jul 13, 2024

JWT with Spring Boot 3 and Spring Security 6

Introduction

  • Learning JWT (JSON Web Token) with Spring Boot 3 and Spring Security 6
  • Importance of securing APIs using Spring Security and JWT
  • Source code available for reference

JWT Validation Mechanism

Request Flow

  1. Incoming HTTP Request: From client/customer to backend (Spring Boot on Apache Tomcat)
  2. Filter Execution: The first execution point in Spring Boot; JWT Authentication Filter is executed first (once per request filter)
    • Internal Check: Check for existence of JWT Token
      • If Missing: Respond with 403 (Forbidden) – Missing JWT token
    • Validation Process:
      1. Extract User Details from the database using UserDetailsService
      2. Fetch User Information: Based on email set as claim/token subject
      3. User Existence Check: If user doesn’t exist, respond with 403
      4. Token Validation:
        • Use JWTService to validate token against the user
        • Respond with 403 if token is invalid
    • Security Context Update:
      1. Set authenticated user in Security Context Holder
      2. Pass request to dispatcher servlet
      3. Execute corresponding controller logic and return response (e.g., 200 OK)

Implementation Steps

Project Setup

  1. Create Spring Boot Project
    • Use Spring Initializer (start.spring.io)
    • Maven project, Spring Boot version 3.0.1, Java 17, JAR packaging
    • Dependencies: Spring Web, Spring Security, JPA, PostgreSQL Driver, Lombok

Configure Database

  1. Setup PostgreSQL
  2. Application Properties
    spring:
      datasource:
        url: jdbc:postgresql://localhost:5432/JWT-Security
        username: amigocode
        password: password
        driver-class-name: org.postgresql.Driver
      jpa:
        hibernate:
          ddl-auto: create-drop
        show-sql: true
        properties:
          hibernate:
            format_sql: true
    

User Entity

  1. Define User Class
  2. Database Entity Annotations
    • Using @Entity, @Table, @Id, @GeneratedValue annotations
    • Auto-generating ID
    • Use Lombok for boilerplate code (getters, setters, constructors)
    • Implement UserDetails interface for Spring Security compatibility
  3. Role Enum: Define User roles (USER, ADMIN)

User Repository

  1. Create User Repository Interface: Extend JpaRepository<User, Integer>
  2. Custom Method: Optional<User> findByEmail(String email)

JWT Authentication Filter

  1. Filter Initialization: Extend OncePerRequestFilter
  2. Filter Logic
    • Retrieve JWT token from HTTP header
    • Extract user email from token using JWTService
    • Validate token and user details
    • Update Security Context Holder

JWT Service

  1. Add JWT-Related Dependencies
    • jjwt-api, jjwt-impl, jjwt-jackson
  2. JWT Token Handling Methods
    • Generate Token, Extract Claims, Validate Token etc.

Security Configuration

  1. Spring Security Configuration
    • Define Security Filter Chain (SecurityFilterChain bean)
    • Disable CSRF
    • Configure session management as stateless
    • Authorized and whitelisted endpoints
    • JWT Filter setup before UsernamePasswordAuthenticationFilter

Authentication and Registration Endpoints

  1. Authentication Controller
    • Define endpoints for registration and authentication
    • Use AuthenticationService for business logic
  2. Json Data Models
    • Define classes for AuthenticationRequest, AuthenticationResponse, and RegisterRequest
  3. Service Layer: Implement registration and authentication logic

Testing and Verification

  1. Execute Application: Ensure application starts without errors
  2. Use Postman for Testing
    • Test secure and open endpoints
    • Verify 403 response for unauthorized access to secured endpoint
    • Verify token generation on registration
    • Verify successful authentication with token

Conclusion

  • Successful implementation of JWT in Spring Boot 3 and Spring Security 6
  • Reminder to follow channel for more content