JWT (JSON Web Token) - sonuprajapati15/Authentication-Authorization GitHub Wiki
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.
- Client - The entity (e.g., web, mobile app) requesting access.
- Authentication Server - Issues JWT tokens after verifying credentials.
- Resource Server - Hosts the protected resources and validates JWT tokens.
- Token Storage - Secure storage of JWT tokens (e.g., HTTP-only cookies, local storage, or in-memory).
- Revocation Mechanism - Ensures compromised tokens can be invalidated (e.g., using blacklists, token expiration, or refresh tokens).
- User Login: The client sends user credentials to the authentication server.
- JWT Token Generation: Upon successful authentication, the server issues an access token (JWT) and optionally a refresh token.
- Token Storage: The client stores the JWT securely (e.g., local storage, HTTP-only cookies, or in-memory).
-
Authorization Request: The client sends the JWT in the request header (
Authorization: Bearer <JWT>
) to access protected resources. - JWT Token Verification: The resource server validates the JWT signature, checks claims, and ensures it is not expired.
- Token Expiry/Renewal: JWT tokens expire after a predefined period and may be refreshed using a refresh token mechanism.
-
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.
-
-
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.
-
Token Storage:
- Access tokens: Stored in HTTP headers (short-lived, stateless).
- Refresh tokens: Stored in HTTP-only cookies or a secure database (long-lived).
-
Middleware for JWT Verification:
- Decodes and verifies the JWT signature.
- Checks expiration time and claims.
-
Access Control:
- Implement role-based or attribute-based access control (RBAC/ABAC).
- Restrict API endpoints based on user permissions.
-
Login Flow:
- User sends credentials → Authentication server validates → Issues JWT access & refresh tokens → Client stores and uses the token.
-
Accessing Protected Resources:
- Client sends JWT token → Resource server validates → Grants or denies access.
-
Token Refresh Flow:
- Client sends refresh token → Authentication server validates → Issues new access token.
-
Logout Flow:
- Client sends a logout request → Refresh token is invalidated.
- 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).
- 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).
- 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.
- 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.
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.
A JWT consists of three parts encoded in Base64 and separated by dots (.
):
Header.Payload.Signature
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"
).
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
}
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.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
Example Signature (Encoded)
3r5Ppmp1ZVqDd7_qjQYBp8h7dXBzQyfsLEU_Jl7upWg
To ensure security, JWTs use cryptographic hashing and signing algorithms.
- 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")
- 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")
- User logs in → The server verifies credentials and generates a JWT.
- Client stores JWT (local storage, HTTP-only cookies, etc.).
-
Client sends JWT in each request (
Authorization: Bearer <token>
). - Server verifies JWT (checks signature and expiration).
- User gets access to protected resources.
Algorithm | Type | Use Case |
---|---|---|
HS256 | Symmetric | Simple applications, internal APIs |
RS256 | Asymmetric | Multi-server, third-party authentication |
ES256 | Asymmetric (ECDSA) | High-security apps, blockchain |
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.