Dung (Donny) Nguyen

Senior Software Engineer

JSON Web Token (JWT)

JSON Web Token (JWT) is a compact, URL-safe method for representing claims securely between two parties. It is commonly used for authentication and information exchange in web applications and APIs.

Structure of JWT

A JWT consists of three parts:

  1. Header: Contains metadata about the token, such as the type (JWT) and the hashing algorithm used (HS256, RS256, etc.).
    {
      "alg": "HS256",
      "typ": "JWT"
    }
    
  2. Payload: Contains the claims or data we want to transmit. For example:
    {
      "sub": "1234567890",
      "name": "John Doe",
      "iat": 1516239022
    }
    

    Common types of claims:

    • Registered Claims: Predefined keys such as iss (issuer), exp (expiration time), sub (subject), and aud (audience).
    • Public Claims: Custom keys shared between parties.
    • Private Claims: Custom keys specific to an application.
  3. Signature: Ensures the token is not tampered with. It is created by hashing the encoded header and payload using a secret or private key:
    HMACSHA256(
      base64UrlEncode(header) + "." + base64UrlEncode(payload),
      secret
    )
    

The three parts are separated by dots, resulting in a token like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

How JWT Works

  1. Authentication:
    • The server generates a JWT upon successful user authentication and sends it to the client.
    • The client stores the token (e.g., in local storage or cookies).
  2. Authorization:
    • For subsequent requests, the client includes the JWT (often in the Authorization header as Bearer <token>).
    • The server verifies the token’s signature and extracts claims to authorize the request.

Advantages

Use Cases

Limitations

For secure implementation, it’s crucial to: