10. Authentication and Tokens
10. Authentication and Tokens
Securing your API starts with choosing the right authentication mechanism and handling tokens with care. A few well-established patterns cover the vast majority of use cases.
Always Use HTTPS
Every API request must travel over TLS. Without it, tokens and credentials are visible to anyone who can inspect network traffic. Enforce HTTPS at the infrastructure level — do not rely on application code alone.
Bearer Tokens
The standard way to authenticate API requests is with a Bearer token in the Authorization header:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
The server validates the token and extracts the identity of the caller. Bearer tokens are simple, stateless, and widely supported by every major HTTP client library.
Access Tokens and Refresh Tokens
Long-lived tokens are a liability. If one leaks, an attacker has access until it expires. Instead, use the short-lived access token plus refresh token pattern:
- The client authenticates once (username/password, OAuth code exchange, etc.) and receives two tokens: a short-lived access token (typically 15 minutes to one hour) and a longer-lived refresh token.
- The client uses the access token for every subsequent API call.
- When the access token expires, the client presents the refresh token to obtain a fresh access token — no re-authentication required.
- To revoke access, the server invalidates the refresh token. The access token becomes useless once it expires naturally.
Best Practices
- Rotate refresh tokens. Issue a new refresh token each time one is used, and invalidate the old one. This limits the damage window if a refresh token is compromised.
- Revoke tokens on suspicious activity. If you detect an unusual login location or pattern, invalidate all active refresh tokens for that account immediately.
- Scope tokens. Where possible, limit each token to the minimum set of permissions the client actually needs. A token used only to read public data should not carry write permissions.
- Store tokens securely on the client. Avoid localStorage in browser applications; prefer httpOnly cookies or in-memory storage to reduce exposure to cross-site scripting attacks.