Delve into the fundamentals of JSON Web Tokens (JWT), their components, and their application in authentication workflows. This guide explains how JWTs work, outlines their decodable nature, and provides coding examples to generate them.
What Is JWT and Its Purpose?
JWT, short for JSON Web Token, is an open standard (RFC 7519) that defines a compact and secure way of transmitting information between two parties, often for authentication. Widely used in distributed systems, microservices, and modern web applications, JWT enables scalable and efficient user verification.
Key Features:
- Compact Format: Allows easy transmission over HTTP, ideal for use in URLs and headers.
- Decentralized Authentication: Works seamlessly across different servers or services.
- Integrity Protection: Ensures that data hasn’t been tampered with, using digital signatures.
Structure of a JWT
JWTs consist of three distinct parts: Header, Payload, and Signature. They're encoded and joined together with a period (.) in a string that looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cA breakdown of each section:
before after
Header
- Typically contains the type of the token (JWT) and the signing algorithm used (e.g., HMAC SHA256).
{
"alg": "HS256",
"typ": "JWT"
}Payload
- Holds the claims (e.g., user information or metadata). Claims can be:
- Registered claims: Standard fields like
iss(issuer) orexp(expiration). - Custom claims: Application-specific data such as a user's role.
- Registered claims: Standard fields like
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}Why JWT Is Decodable: Implications
JWTs are designed to be readable and easily transmitted. Their payload is Base64Url-encoded, making it straightforward for anyone to decode and inspect.
JWT Authentication Workflow
The following steps outline how JWTs function in an authentication workflow:
steps
- User Login: A user provides credentials (username and password) to authenticate with the server.
- JWT Issuance: Upon authentication, the server issues a JWT containing relevant claims like the user's ID and role.
- Token Storage: The JWT is stored either in the browser's
localStorageor as a secure cookie. - Token Usage: The user sends the JWT with every API request (usually in the
Authorizationheader). - Server Verification: The server verifies the JWT signature and extracts claims to authorize the request.
Refresh Token Usage and Rotation
Access tokens (JWTs) typically have limited lifespans to minimize the impact of compromise. For prolonged sessions, refresh tokens are used to generate new access tokens.
When to Use Refresh Tokens
- Enable Automatic Renewals: Use refresh tokens to extend user sessions without requiring them to log in repeatedly.
- Token Rotation: Each time a refresh token is used, issue a new one and invalidate the old one. If a stolen token is reused, the server can detect it.
- Storage Considerations: Place refresh tokens in an
HttpOnlycookie to prevent access via JavaScript (reducing XSS risks).
Coding Example: Generating a JWT
Here's a practical implementation of generating JWTs using Python's PyJWT library.
Install PyJWT
pip install PyJWTBelow is an example of encoding a JWT:
import jwt
import datetime
# Define the secret key and the payload
secret_key = "your-secure-secret"
payload = {
"user_id": 12345,
"role": "admin",
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}
# Generate the JWT
jwt_token = jwt.encode(payload, secret_key, algorithm="HS256")
print("Generated JWT:", jwt_token)This code creates a token with user-specific claims and a one-hour expiration.
JWT Storage Trade-offs
Choosing where to store JWTs depends on your application's security needs.
comparison
Cookies
- Can be
HttpOnly, reducing the risk of XSS. - Use
SameSiteandSecureflags to enforce secure transmission. - Automatically sent with requests to the same domain.
LocalStorage
- Provides greater flexibility for client-side operations.
- Susceptible to XSS if the application is not properly secured.
Choose cookies for security-sensitive applications or cases requiring cross-site request forgery (CSRF) protection.
FAQ
Can you explain the structure of a JWT?
A JWT consists of three parts — Header, Payload, and Signature — joined by periods. The header contains metadata, the payload includes claims, and the signature ensures the token's integrity.
Why is JWT easily decodable?
JWT payloads are Base64Url-encoded, allowing them to be decoded by anyone. This makes them unsuitable for storing sensitive information but ideal for transmitting verification data.
Should I use localStorage or cookies for JWTs?
Cookies are safer due to HttpOnly and Secure flags, preventing access by JavaScript. However, localStorage provides more flexibility but requires stronger XSS protections.
What problem does refresh token rotation solve?
Refresh token rotation improves security by invalidating old tokens after use, limiting the lifespan of stolen credentials.
Official reference: JSON Web Token introduction.