Best Practices for Access, ID, and Refresh Tokens
When building modern applications with OAuth 2.0 and OpenID Connect, developers often get confused about where to store tokens. This decision is crucial because storing them incorrectly can open doors to serious vulnerabilities like XSS or CSRF attacks. Let’s break it down.
Understanding the Tokens
-
Access Token → Proves what you can do. It authorizes the client to call APIs on behalf of the user.
-
ID Token → Proves who you are. It carries identity information (name, email, roles) about the authenticated user.
-
Refresh Token (optional) → Used to obtain new access tokens without making the user log in again.
Each token has a different lifespan and security sensitivity, so the storage strategy must match the risk.
Storage on the User Side (Frontend)
1. Web Applications
-
Best practice: Keep tokens in memory (JavaScript variables).
-
Safer persistence: Use HTTP-only, Secure cookies if tokens must survive page reloads.
-
Avoid:
localStorageandsessionStoragefor tokens. They’re vulnerable to cross-site scripting (XSS).
2. Mobile Applications
-
Use platform-provided secure storage:
-
iOS → Keychain
-
Android → Encrypted Shared Preferences or Keystore
-
This ensures tokens are protected even if the device is compromised at the application level.
Storage on the Backend (Server/API)
Access Tokens
-
Typically not stored long-term.
-
The server simply validates the token on each request (signature, issuer, audience, and expiry).
-
Some apps keep metadata (like
userId → lastAccessToken) in a database or cache (e.g., Redis), but this is optional.
ID Tokens
-
Often used only during the login process.
-
The backend can extract user claims (email, roles, permissions) and store them in a session or database instead of keeping the raw token.
Refresh Tokens
-
Must be stored securely because they live longer.
-
Store in an encrypted database or secure cache.
-
On the client, prefer HTTP-only Secure cookies.
Putting It All Together
-
Frontend → Short-lived storage in memory or secure cookies.
-
Backend → Validate tokens per request; securely store refresh tokens if required.
-
Rule of thumb: Never expose long-lived tokens (like refresh tokens) to JavaScript or client-side storage.
Comments
Post a Comment