JWT (JSON Web Token) is a compact token format used in many web applications and APIs for token-based authentication and controlled data exchange between clients and servers. It is often chosen because a server can validate a signed token without keeping traditional session state for every request.
This guide explains the basic structure of a JWT, how a typical authentication flow works, where JWTs are useful, and which security practices matter when using them in production systems.
What is JWT?
A JWT is a JSON-based token format used to carry claims about a user, client, or request. In authentication flows, the server issues a signed token after a successful login. The client then sends that token with later API requests so the server can validate the request and decide whether access should be allowed.
A JWT is made of three Base64URL-encoded parts separated by periods:
- Header: identifies the token type and signing algorithm.
- Payload: contains claims such as the subject, issued-at time, or other token data.
- Signature: helps the server detect whether the token has been changed.
Where JWT Fits in Authentication
JWTs are commonly used for API authentication, user sessions in web applications, and cross-service authorization patterns. Instead of looking up server-side session data on every request, the server can inspect the token and verify the signature.
This stateless model can simplify scaling across multiple servers, but it also means the token itself must be protected carefully. If a valid token is stolen, an attacker may be able to reuse it until it expires or is otherwise invalidated.
JWT Structure
Header
The header contains metadata about the token. It usually identifies the token type and the signing algorithm.
{
"alg": "HS256",
"typ": "JWT"
}
- alg: the algorithm used to sign the token, such as HMAC SHA256.
- typ: the token type, commonly JWT.
Payload
The payload contains claims. Claims describe information associated with the token, such as a user identifier, user-related data, or timing information.
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
- sub: a subject identifier, often used as a user ID.
- name: user-related information.
- iat: the issued-at timestamp, represented as Unix time.
Keep payloads focused. Large payloads increase token size, and unnecessary claims make token handling harder to manage.
Signature
The signature is created from the encoded header, encoded payload, and a secret or private signing key. The server checks this signature when it receives the token.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
If the header or payload changes after signing, signature validation should fail. This is what allows the server to detect tampering.
How JWT Authentication Works
A typical JWT authentication flow follows these steps:
- User authentication: the user submits credentials, such as a username and password.
- Token issuance: after validating the credentials, the server issues a signed JWT.
- Client storage: the browser or mobile app stores the token, often in a cookie or another client-side storage mechanism.
- Request authentication: the client sends the token with later API requests, commonly in the
Authorizationheader. - Token validation: the server validates the signature and checks relevant claims, such as expiration.
- Resource access: when the token is valid, the server returns the requested resource or data.
GET /protected-resource HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Storage, Expiration, and Refresh Tokens
Where a JWT is stored has a direct effect on security. Local storage can be simple to implement, but it is exposed to cross-site scripting risks. Cookies can support stronger protections such as the Secure and HttpOnly attributes when configured correctly.
JWTs should usually have an expiration time. A short-lived access token limits the useful lifetime of a stolen token. For better usability, systems often pair short-lived access tokens with refresh tokens that are managed more carefully.
When using refresh tokens, plan how they are stored, rotated, and invalidated. Logout, suspected compromise, and credential changes should all have a clear token invalidation strategy.
Benefits of JWT
Stateless authentication
Because authentication information is carried in the signed token, the server does not need to maintain a traditional session record for every request. This can make horizontal scaling simpler.
Flexible token contents
JWTs can carry claims used for authentication and authorization decisions. For example, a token can include identifiers or permissions that help the server decide which resources a request may access.
Useful for API-oriented systems
JWTs fit naturally into API-based applications, mobile apps, and cross-domain architectures where the client sends a bearer token with each request.
JWT Security Best Practices
- Use strong secrets or keys. Weak signing secrets make token tampering easier to attempt.
- Require HTTPS. Tokens should be transmitted only over encrypted connections.
- Set short access-token lifetimes. Short expiration windows reduce the impact of token theft.
- Use appropriate signing algorithms. Avoid outdated or unsuitable algorithms, and choose options such as HMAC-SHA256 or RSA based on your architecture.
- Minimize payload data. Keep only the claims needed for authentication and authorization decisions.
- Plan invalidation. Use token tracking, blacklists, or issuance-history checks when logout or compromise scenarios require revocation.
Limitations and Trade-Offs
JWTs are useful, but they are not a complete security design on their own. Teams still need careful storage, expiration, validation, and revocation practices.
Two practical trade-offs deserve attention:
- Token size: every claim increases the amount of data sent with requests, so large payloads can affect network efficiency.
- Token theft risk: a stolen token can be reused while it remains valid, so storage controls and short expiration times are important.
Related Implementation Topics
If you are applying JWTs in a specific framework or API platform, these related guides may also help:
- FastAPI Security Best Practices: From Authentication and Authorization to CORS
- Building a Robust API Platform with Laravel, REST, JSON:API, GraphQL, and OpenAPI
Conclusion
JWT is a practical option for token-based authentication in web applications and APIs. It gives teams a compact way to carry signed claims, validate requests, and reduce dependence on server-side session state.
For secure use, treat JWT as one part of a broader authentication design. Use strong signing keys, require HTTPS, keep access tokens short-lived, minimize payload data, and prepare a clear strategy for compromised or expired tokens.
greeden helps turn ideas into reliable systems through flexible software design and system development support. If you have questions or want to discuss a project, contact us here.
