Bearer Tokens
On this page
What a bearer token is
A bearer token is a credential that grants access to an API. “Bearer” means: whoever possesses the token can use it. That is why transport security, storage rules, and expiry matter.
Authorization header format
Authorization: Bearer <access_token>
Example request
GET /api/me Authorization: Bearer eyJhbGciOi... Accept: application/json
Token properties you should design
- Expiry: short-lived access tokens reduce damage if leaked
- Audience: token should be valid only for a specific API
- Scopes/permissions: least privilege access
- Revocation strategy: what happens when you must invalidate tokens
Storage rules (very important)
- Do not store bearer tokens in localStorage if you can avoid it (XSS risk).
- For browser apps, consider secure cookies (HttpOnly + SameSite) when appropriate.
- For mobile/server apps, use secure storage (keychain/keystore/env vars).
- Never include tokens in URLs (they leak via logs and referrers).
401 vs 403
- 401 Unauthorized: missing/invalid/expired token
- 403 Forbidden: valid token but not allowed
Example: expired token
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"title": "Unauthorized",
"status": 401,
"detail": "Token is expired."
}
Common mistakes
- Long-lived access tokens with no refresh strategy
- Tokens in query strings
- Returning 200 with “auth failed” JSON instead of 401/403
Checklist
- Access tokens expire quickly.
- Tokens are sent only via Authorization header or secure cookies.
- 401/403 are used correctly.