How JWT tokens secure APIs
· Category: API & REST
Short answer
JSON Web Tokens are compact, self-contained tokens that carry claims and a signature, enabling stateless authentication.
Steps
- The issuer creates a JWT with a header, payload containing claims, and a signature.
- The client includes the JWT in the Authorization header as a bearer token.
- The API verifies the signature using a shared secret or public key.
- The API checks claims such as expiration time and issuer validity.
- The request is authorized based on scopes or roles embedded in the token.
Tips
- Keep JWT payloads small to avoid bloating request headers.
- Use short expiration times and refresh tokens to limit compromise windows.
- Sign tokens with strong algorithms such as RS256 instead of weaker alternatives.
- Validate all claims including not-before and audience to prevent replay attacks.
Common issues
- Storing sensitive data in JWT payloads which are merely base64 encoded.
- Failing to verify signatures allowing token forgery.
- Clock skew causing valid tokens to be rejected.
- Inability to revoke tokens immediately without maintaining a deny list.
Example
GET /api/protected HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
This request demonstrates how to include a bearer token in the Authorization header to access a protected API endpoint securely.