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:
- Header: Contains metadata about the token, such as the type (
JWT
) and the hashing algorithm used (HS256
,RS256
, etc.).{ "alg": "HS256", "typ": "JWT" }
- 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), andaud
(audience). - Public Claims: Custom keys shared between parties.
- Private Claims: Custom keys specific to an application.
- Registered Claims: Predefined keys such as
- 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
- 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).
- Authorization:
- For subsequent requests, the client includes the JWT (often in the
Authorization
header asBearer <token>
). - The server verifies the token’s signature and extracts claims to authorize the request.
- For subsequent requests, the client includes the JWT (often in the
Advantages
- Compact: Suitable for URLs, cookies, and headers.
- Self-contained: Contains all necessary information for validation.
- Stateless: Server doesn’t need to maintain session state.
Use Cases
- Authentication (e.g., Single Sign-On, API authentication).
- Information exchange where tamper-proof and verifiable data is needed.
Limitations
- Cannot be revoked: Unless stored in a revocation list or using short-lived tokens with refresh tokens.
- Payload is visible: Though it’s signed, the data is not encrypted and can be decoded by anyone.
For secure implementation, it’s crucial to:
- Use HTTPS to prevent token interception.
- Use strong secrets/keys for signing.
- Set expiration times (
exp
) and validate them.