OAuth Tokens: Expiry, Refresh and Rotation

9 min read

483
OAuth Tokens: Expiry, Refresh and Rotation

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:

  1. Record the expires_in value from the token response and schedule refresh early with a small safety margin.
  2. On refresh, overwrite the stored refresh token with the newest one from the response before any other requests proceed.
  3. Serialize refresh so only one refresh request runs at a time per user session.
  4. On refresh failure, clear session state and re-authenticate rather than retrying in a tight loop.
  5. 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.

Was this article helpful?

Your feedback helps us improve our editorial quality

Latest Articles

Automation 23.10.2026

API Rate Limits: Requests per Minute and Burst Limits

API rate limits control how often an app can call a service, using requests per minute and burst limits. This matters for developers, QA teams, and anyone integrating health-adjacent systems that must stay reliable under load. You’ll learn what RPM and burst mean, how common limit errors happen, how to design retry and backoff, and how to test throttling safely. The article also covers practical checklists, comparison guidance, and a short FAQ for real integration scenarios.

Read » 600
Automation 01.12.2026

Workflow Runs: Cost per Successful Execution

Workflow runs measure how often an automated job finishes its intended work. This article explains cost per successful execution for teams using health data pipelines, scheduling, and background jobs. It helps readers interpret run metrics, separate success from retries, and estimate costs from logs and billing. You will learn how to define “successful,” track failure modes, and compare approaches using a practical checklist and examples.

Read » 354
Automation 08.11.2026

Human Approval: Where Automation Should Pause

This article explains how “human approval” works in automated health workflows, from symptom checkers to prior authorization and lab result alerts. It’s for patients, caregivers, and informed readers who want to judge when automation should act and when a clinician or staff member must review. You’ll learn the failure modes that trigger manual review, the supporting systems behind automation, and practical steps to ask better questions, document context, and reduce delays without losing safety.

Read » 235
Automation 17.10.2026

Webhooks: Duplicate Events and Retry Delivery

Webhooks send event notifications from one system to another, but duplicate deliveries and retries happen in real deployments. This article explains why duplicates occur, how retry delivery works, and what to do when your webhook endpoint receives the same event multiple times. It is for developers and operations teams who connect apps, CRMs, payments, or health-adjacent workflows and need reliable processing. You will learn practical idempotency patterns, verification steps, and common failure modes.

Read » 586
Automation 12.11.2026

Idempotency Keys: Preventing Duplicate Runs

Idempotency keys help systems avoid duplicate actions when requests get retried, timed out, or delivered twice. This guide explains how idempotency keys work in APIs and background jobs, why duplicates still happen without them, and how to choose key scope, storage, and expiry. Readers will learn practical patterns, common failure modes, and how to test behavior so payments, bookings, and health-related workflows do not run twice.

Read » 485
Automation 04.11.2026

Automation Errors: Retry or Fail Fast?

Automation errors happen when systems misread state, time out, or hit partial failures. This article explains how retry logic and fail-fast behavior work in real services and scripts, why each approach breaks in specific ways, and how to choose based on error type, idempotency, and rate limits. Readers will learn practical patterns, safe backoff settings, and how to test failure handling so automated workflows stay reliable.

Read » 520