Spring Boot HandBook

    Introduction :#

    JWT (JSON Web Token) is a popular method for securely transmitting information between parties as a JSON object. It is commonly used for authenticating and authorizing requests in web applications. Here's an overview of how JWT authentication works:

    How JWT Authentication Works:#

    1. User SignUp:
    2. User Login:
    3. Token Generation:
    4. Token Structure:
    5. Client-Side Storage:
    6. Authenticated Requests:
    7. Token Validation:
    8. Token Expiration:
    9. Security Considerations:

    Example Workflow#

    1. User SignUp:

      1. POST /signUp
         
    2. User LogIn:

      1. POST /login
      2. Response: JWT
         
    3. Access Protected Resource:

      1. GET /user/profile
      2. Header: Authorization: Bearer <JWT>
         
    4. Server Validates JWT:

      1. If valid, the server processes the request and returns the requested resource.
      2. If invalid, the server responds with a 401 Unauthorized error.
         

    Using JWT For Authentication:#

    Login Workflow with JWT:#

    Authentication Workflow with JWT:#

    JWTAuthFilter Control Flow:#

    Implementation in Code:#

    1. How to authenticate future request that come into the server
    2. How to authenticate all the request that contain a token
    3. The provided token is valid or not
    4. If it is valid then how to pass the authentication object inside the spring security context holder so that it is available to all the controllers.

    let's break down each step:

    • Authenticate Future Requests with JWT

    When a user logs in, they receive a JWT. This token is included in the Authorization header of every subsequent request. The server must then authenticate each request using this JWT.
     

    • Authenticate Requests that Contain a Token

    You need to intercept every request and check if it has a valid JWT token. If it does, the server will authenticate the user based on the token.
     

    • Check if the Token is Valid

    The server will validate the JWT token by checking its signature, expiration date, and possibly other claims.
     

    • Pass the Authentication Object to Spring Security Context Holder

    If the token is valid, you'll create an Authentication object and store it in the SecurityContextHolder, which makes the authenticated user available throughout the application (e.g., in controllers).
     

    Last updated on Dec 09, 2024