JWT (JSON Web Token) - sonuprajapati15/Authentication-Authorization GitHub Wiki

Token-Based Authentication and Authorization - System Design (JWT)

High-Level Design (HLD)

Overview

JWT (JSON Web Token) based authentication and authorization is a mechanism to securely validate users and control access to resources using cryptographically signed tokens instead of traditional session-based authentication.

Components

  1. Client - The entity (e.g., web, mobile app) requesting access.
  2. Authentication Server - Issues JWT tokens after verifying credentials.
  3. Resource Server - Hosts the protected resources and validates JWT tokens.
  4. Token Storage - Secure storage of JWT tokens (e.g., HTTP-only cookies, local storage, or in-memory).
  5. Revocation Mechanism - Ensures compromised tokens can be invalidated (e.g., using blacklists, token expiration, or refresh tokens).

Workflow

  1. User Login: The client sends user credentials to the authentication server.
  2. JWT Token Generation: Upon successful authentication, the server issues an access token (JWT) and optionally a refresh token.
  3. Token Storage: The client stores the JWT securely (e.g., local storage, HTTP-only cookies, or in-memory).
  4. Authorization Request: The client sends the JWT in the request header (Authorization: Bearer <JWT>) to access protected resources.
  5. JWT Token Verification: The resource server validates the JWT signature, checks claims, and ensures it is not expired.
  6. Token Expiry/Renewal: JWT tokens expire after a predefined period and may be refreshed using a refresh token mechanism.

Low-Level Design (LLD)

Authentication Server

  1. Endpoints:

    • /login: Accepts user credentials and returns JWT access & refresh tokens.
    • /refresh-token: Issues a new access token when the refresh token is valid.
    • /logout: Invalidates refresh tokens.
  2. JWT Token Generation:

    • Use JWT with claims such as user ID, roles, and expiration time.
    • Sign JWT tokens using HMAC (HS256) or RSA (RS256) algorithms.
  3. Token Storage:

    • Access tokens: Stored in HTTP headers (short-lived, stateless).
    • Refresh tokens: Stored in HTTP-only cookies or a secure database (long-lived).

Resource Server

  1. Middleware for JWT Verification:

    • Decodes and verifies the JWT signature.
    • Checks expiration time and claims.
  2. Access Control:

    • Implement role-based or attribute-based access control (RBAC/ABAC).
    • Restrict API endpoints based on user permissions.

JWT Flows

  1. Login Flow:

    • User sends credentials → Authentication server validates → Issues JWT access & refresh tokens → Client stores and uses the token.
  2. Accessing Protected Resources:

    • Client sends JWT token → Resource server validates → Grants or denies access.
  3. Token Refresh Flow:

    • Client sends refresh token → Authentication server validates → Issues new access token.
  4. Logout Flow:

    • Client sends a logout request → Refresh token is invalidated.

Pros and Cons

Pros:

  • Stateless and scalable (JWT does not require server-side session storage).
  • Compact and portable (suitable for web, mobile, and microservices architectures).
  • Secure when properly implemented (signed and optionally encrypted tokens).
  • Supports Single Sign-On (SSO).

Cons:

  • Token management complexity (expiration, storage, and revocation handling).
  • JWT tokens can be stolen if not secured properly.
  • Harder to revoke JWTs compared to session-based authentication (workarounds: token blacklisting, short expiry, refresh tokens).

When to Use JWT?

  • API-based authentication (e.g., mobile apps, microservices, third-party integrations).
  • Single sign-on (SSO) across multiple domains or services.
  • Distributed architectures where scalability is a priority.

When Not to Use JWT?

  • Simple applications without API requirements (session-based auth might be simpler).
  • When token revocation is a critical requirement (JWTs are harder to revoke compared to session-based authentication).

This document provides a structured design approach for implementing JWT-based authentication and authorization in a secure and scalable manner.

JWT (JSON Web Token) Components & Hashing Strategy

A JWT (JSON Web Token) is a compact and secure way to transmit information between parties. It is widely used for authentication and authorization in APIs and web applications.


1. Components of JWT

A JWT consists of three parts encoded in Base64 and separated by dots (.):

Header.Payload.Signature

1.1 Header

The Header contains metadata about the token, such as the algorithm used for signing and the type of token.

Example Header (Base64 Encoded)

{
  "alg": "HS256",
  "typ": "JWT"
}
  • alg (Algorithm) - Specifies the hashing algorithm (e.g., HS256, RS256).
  • typ (Type) - Defines the type of token (always "JWT").

1.2 Payload

The Payload contains claims (data about the user or session). These claims are categorized into three types:

  • Registered claims (predefined, optional): iss (issuer), exp (expiration), sub (subject).
  • Public claims (custom claims): user_id, role, email.
  • Private claims (specific to an application): Any application-specific data.

Example Payload (Base64 Encoded)

{
  "user_id": 123,
  "role": "admin",
  "exp": 1691234567
}

1.3 Signature

The Signature ensures the token's integrity by verifying it hasn’t been altered. It is created by encoding the Header and Payload using a hashing algorithm and a secret key.

Signature Formula:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

Example Signature (Encoded)

3r5Ppmp1ZVqDd7_qjQYBp8h7dXBzQyfsLEU_Jl7upWg

2. Hashing & Signing Strategies

To ensure security, JWTs use cryptographic hashing and signing algorithms.

2.1 Symmetric Algorithms (HMAC)

  • Example: HS256 (HMAC + SHA-256)
  • Uses one secret key to sign and verify the token.
  • Pros: Fast and easy to implement.
  • Cons: Less secure in distributed environments (as the secret key must be shared).

Example (HS256 Signature)

import jwt

token = jwt.encode({"user_id": 123}, "secret_key", algorithm="HS256")

2.2 Asymmetric Algorithms (RSA, ECDSA)

  • Example: RS256 (RSA + SHA-256)
  • Uses a private key for signing and a public key for verification.
  • Pros: More secure; allows token verification without exposing the private key.
  • Cons: Slower compared to HMAC.

Example (RS256 Signature)

private_key = "-----BEGIN PRIVATE KEY-----\n..."
token = jwt.encode({"user_id": 123}, private_key, algorithm="RS256")

3. How JWT Works in Authentication

  1. User logs in → The server verifies credentials and generates a JWT.
  2. Client stores JWT (local storage, HTTP-only cookies, etc.).
  3. Client sends JWT in each request (Authorization: Bearer <token>).
  4. Server verifies JWT (checks signature and expiration).
  5. User gets access to protected resources.

4. When to Use Which Algorithm?

Algorithm Type Use Case
HS256 Symmetric Simple applications, internal APIs
RS256 Asymmetric Multi-server, third-party authentication
ES256 Asymmetric (ECDSA) High-security apps, blockchain

Conclusion

JWTs provide a secure, stateless authentication mechanism when properly implemented. Choosing the right hashing strategy depends on the security level and architecture of the application.

⚠️ **GitHub.com Fallback** ⚠️