OAuth Tokens And Lifetimes
OAuth 2.0 issues tokens that represent authorization, not identity. An access token is typically short-lived and sent to an API as a bearer credential. A refresh token is longer-lived and used to obtain new access tokens without re-prompting the user. Token behavior depends on the authorization server’s policy, so two apps can use the same OAuth flow and still have different expiry times.
In practice, you see this when an app stops working after some time even though you did not log out. The app calls an API, receives an error such as invalid_token or expired, then tries a refresh. If refresh fails, the app usually forces a re-login. That pattern is normal, but the details matter because refresh tokens can be a higher-value target than access tokens.
OAuth also defines token types and claims, such as scope and sometimes aud (audience). Some access tokens are opaque strings that the server must introspect, while others are JWTs that clients can decode. Decoding a JWT does not grant access by itself; the API still validates it.
Expiry, Refresh, And Rotation
Access token expiry is usually enforced by the authorization server and validated by the API. For JWT access tokens, expiry is typically carried in the exp claim. For opaque tokens, expiry is enforced server-side during introspection. Either way, the API rejects tokens after expiry, and the client must refresh or re-authenticate.
Refresh token usage is governed by the authorization server’s rules. Some servers require refresh tokens to be used only once, which is where rotation enters. Rotation means each refresh request returns a new refresh token and invalidates the previous one. This reduces the window in which a stolen refresh token remains usable, but it introduces a race condition risk when multiple refresh requests happen at the same time.
Rotation also changes how you should reason about logout. A “logout” action may revoke refresh tokens, but some systems revoke only the current session token or require additional calls to a revocation endpoint. If revocation is not complete, a previously issued refresh token might still work until its policy expires or is revoked. The exact behavior depends on the provider and the OAuth implementation.
Solutions And Practical Advice
Set Expectations For Expiry
Check the authorization server documentation or the app’s network calls to learn the actual access token lifetime. In many systems, access tokens expire in the range of 5 to 60 minutes, while refresh tokens last much longer, but the only reliable number is what the server issues. If you control the client, log the expires_in value returned during token exchange and compare it with observed failures.
If you are debugging a client, treat “expired token” errors as a normal branch, not an exception. A careful client refreshes before expiry when possible, using a small safety margin for clock skew. A common margin is 30 to 120 seconds, and I have seen teams pick 60 seconds after a production incident caused by mismatched device clocks.
Use Refresh With Rotation Safety
When rotation is enabled, store the newest refresh token immediately after a successful refresh response. If your client makes concurrent API calls, add a single-flight mechanism so only one refresh request runs at a time. Without that, two requests can refresh simultaneously, and one will invalidate the other’s refresh token, leading to a forced re-login.
In OAuth libraries, look for built-in token managers that serialize refresh operations. If you roll your own, add a mutex around refresh and keep the latest refresh token in memory plus secure persistent storage. For web apps, prefer server-side session storage or secure cookies when the architecture supports it, because browser storage choices affect exposure to XSS.
Plan For Revocation And Logout
Use the provider’s revocation endpoint or logout mechanism that maps to refresh token revocation. Many systems expose an OAuth token revocation endpoint (RFC 7009), but the exact parameters and behavior vary. After revocation, expect that already-issued access tokens might still work until they expire, since revocation often targets refresh tokens rather than access tokens.
For user-facing behavior, treat logout as “stop future refresh,” not “instantly invalidate every access token everywhere.” If you need immediate access cut-off, some systems support short access token lifetimes or token introspection checks that reflect revocation state, but that depends on the provider.
Validate Token Claims And Audience
APIs should validate issuer, audience, signature, and expiry. For JWT access tokens, verify the aud claim matches the API identifier and confirm the iss claim matches the expected authorization server. For opaque tokens, use introspection and check the returned active status and scopes.
Do not rely on client-side decoding for security decisions. Decoding a JWT without verifying the signature does not prove authenticity. If you see apps that “check exp in the browser” and then proceed, that pattern is insecure because it bypasses server validation.
Case Examples For Real Scenarios
Race Condition During Refresh
An anonymized mobile app calls two APIs at the same time after the access token expires. Both requests receive an expired token error and trigger refresh. The authorization server uses refresh token rotation and invalidates the old refresh token on first use. The second refresh attempt fails, and the app clears the session, forcing the user to log in again. The fix is to serialize refresh and update stored refresh tokens only from the winning refresh response.
Opaque Tokens With Introspection Latency
An anonymized web service uses opaque access tokens and validates them via an introspection endpoint. During a brief network issue, introspection calls time out, and the API returns errors even though the tokens are still valid. The client interprets the errors as authentication failures and repeatedly refreshes, increasing load. The mitigation is to add retry logic with backoff for introspection failures, distinguish “inactive token” from “introspection unavailable,” and avoid refresh storms.
Comparison Table And Checklist
| Topic | Access Token Expiry | Refresh Token | Rotation Behavior |
|---|---|---|---|
| What changes | Token stops being accepted by the API | Used to obtain new access tokens | Old refresh token is invalidated after use |
| Typical failure | invalid_token or expired token | invalid_grant or revoked refresh | refresh fails after concurrent refresh calls |
| What to check | exp, clock skew, API validation path | refresh response, storage update timing | single-flight refresh and token overwrite rules |
| Practical goal | Avoid mid-session API failures | Reduce re-login frequency safely | Limit replay risk from stolen refresh tokens |
Step-by-step checklist for a client that supports refresh token rotation:
- Record the expires_in value from the token response and schedule refresh early with a small safety margin.
- On refresh, overwrite the stored refresh token with the newest one from the response before any other requests proceed.
- Serialize refresh so only one refresh request runs at a time per user session.
- On refresh failure, clear session state and re-authenticate rather than retrying in a tight loop.
- Log token error codes like invalid_grant and correlate them with refresh attempts and timestamps.
If you are using a library, check its version and behavior. I once saw a team upgrade to a token manager version labeled “1.4.2” and accidentally reintroduced concurrent refresh because the new default changed how promises were cached.
Common Mistakes That Break Trust
One mistake is treating token expiry as a user problem. If an app refreshes too late, users see repeated sign-in prompts, and support tickets follow. A better approach measures token lifetimes and refresh timing in logs, then adjusts the refresh schedule.
Another mistake is storing refresh tokens in places that increase exposure. For browser apps, local storage can be read by injected scripts, and that risk does not disappear when tokens are “short-lived.” For native apps, storing tokens in plain files or shared keychains can also widen the attack surface.
Teams also mis-handle rotation by not updating refresh tokens atomically. If a refresh succeeds but the client fails to persist the new refresh token, the next refresh attempt uses an invalidated token. This often shows up after app restarts, and it is easy to miss during short testing sessions.
Finally, some implementations hide errors. If the client swallows invalid_grant and retries refresh repeatedly, it can create refresh storms and lock out users. A mild frustration point: many teams copy-paste retry logic from HTTP examples and forget that OAuth errors often require a re-auth flow.
FAQ
How Long Do Access Tokens Last?
Access token lifetimes are set by the authorization server and can range from minutes to hours. The only reliable way to know for a specific service is to inspect the token response fields such as expires_in or the exp claim in JWTs.
What Happens When A Refresh Token Expires?
When the refresh token is expired or revoked, the refresh request typically fails with an OAuth error such as invalid_grant. The client then needs the user to re-authenticate to obtain a new refresh token.
Does Refresh Token Rotation Change Security?
Rotation reduces the replay window for stolen refresh tokens by invalidating the previous token after use. It also increases the need for correct client behavior, especially around concurrent refresh requests and atomic storage updates.
Can An Expired Access Token Be Reused?
No. APIs reject expired access tokens based on expiry validation, either through JWT exp checks or opaque token introspection. Reusing an expired token should trigger refresh or re-login, not continued API calls.
Why Do I Get Invalid Token Errors After Logging In?
Common causes include clock skew, using the wrong token type, sending the token to the wrong audience API, or failing to update stored tokens after refresh. Checking the exact error code and the token’s aud and exp values helps narrow it down.
Author's Insight
OAuth token expiry and refresh behavior are governed by the authorization server’s policy, so “correct” handling depends on the exact error codes and token response fields your service returns. Rotation adds a race condition risk that client code must handle by serializing refresh and persisting the newest refresh token immediately. For debugging, logging token error codes with timestamps and correlating them to refresh attempts usually reveals the root cause faster than guessing. If you are designing a health-adjacent integration, treat refresh tokens as high-value credentials and align storage and logout behavior with the provider’s revocation semantics.
Key Takeaways
- Access tokens expire quickly and should trigger refresh or re-auth, not repeated API retries.
- Refresh tokens extend sessions, and rotation invalidates older refresh tokens after use.
- Concurrent refresh calls are a common rotation failure mode, so serialize refresh per session.
- Validate token claims on the API side and do not rely on client-side decoding for security.
- Logout and revocation often target refresh tokens first, so access tokens may still work until expiry.