Prevent 401: Token Refresh Done Right

Prevent 401: Token Refresh Done Right

Written by

in

Lab-tested: Python 3.13.5 mock OAuth API · 2 Dec 2026 · Reproduced and fixed in our lab

Fix Box — Try This First (10 Seconds)

Most "random" 401s are just expired access tokens. Refresh proactively at 80% of the token lifetime instead of waiting for a 401.

When you do get a 401, refresh once and retry once — never loop with the same token. With rotating refresh tokens, always store the newest one and discard the old.

Start from the pillar 401 Unauthorized: Causes and How to Fix It or check your endpoint with the 401 Checker.

Table of Contents

Why Expiry Causes Most 401s

Access tokens are short-lived on purpose. A one-hour token means every long-running client will eventually present an expired one.

If the client treats that 401 as a hard failure, users see random logouts. If it retries blindly, it hammers the API with a dead token.

The refresh token exists to solve exactly this. The client exchanges it for a fresh access token without bothering the user.

Done well, expiry becomes invisible. Done badly, it produces 401 storms, reuse alarms, and forced logouts.

The Exact Responses (Verbatim from Our Lab)

Our lab mock OAuth API issued 6-second access tokens so expiry was observable in one test run. Captures from 2 Dec 2026, token values shortened:

# Expired access token
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token", error_description="The access token expired"

# Refresh grant succeeds, new pair issued
HTTP/1.0 200 OK
{"access_token": "at_...", "refresh_token": "rt_...", "expires_in": 6, "token_type": "Bearer"}

# Old refresh token reused after rotation
HTTP/1.0 400 Bad Request
{"error": "invalid_grant", "error_description": "Refresh token invalid or already used (rotation)"}

Two details matter. The expired-token 401 names the problem in error_description. The refresh failure is a 400 invalid_grant, not a 401 — that is the RFC 6749 convention, and clients must handle both.

Pattern 1: Reactive Refresh (401, Then Refresh)

The baseline pattern: send the request, and on 401 with error="invalid_token", refresh and retry the original request exactly once. In our lab this turned an expired-token 401 into a 200 on the retry.

Reactive refresh is simple and works everywhere. Its cost is one wasted round trip per expiry, and it fails when the request is not safe to replay.

Cap it at one retry. A second 401 after a successful refresh means something else is wrong — stop and surface the error.

Pattern 2: Proactive Refresh (Before Expiry)

Better: track expires_in and refresh at 80% of the lifetime. The client never presents a dead token, so users never see the 401 at all.

In our lab, refreshing at 4 seconds into a 6-second lifetime produced a clean 200 with no 401 anywhere in the log.

Proactive refresh needs a timer or a check before each request. The check-before-request variant is simpler and survives laptop sleep: before sending, if the token expires within the next 30 seconds, refresh first.

Either way, leave margin for network latency and clock differences.

Pattern 3: Rotation and Reuse Detection

Modern authorization servers rotate refresh tokens: every exchange returns a new refresh token and invalidates the old one. RFC 9700 requires rotation or sender-constraining for public clients, precisely so a stolen token has a one-use window.

Our lab enforced rotation. Reusing the old refresh token after a successful exchange returned 400 invalid_grant.

In production systems with reuse detection, that replay can revoke the whole token family and log the user out everywhere — by design, because the server cannot tell thief from owner.

Two client bugs trigger false reuse alarms. Concurrent requests that both refresh with the same token race each other.

A lost refresh response leaves the client holding a retired token. Make refresh single-flight: one in-progress refresh shared by all callers, and always persist the newest refresh token atomically.

Pattern 4: Clock Skew and the nbf Trap

Tokens can also fail for being "too new." If the issuing server's clock runs ahead, the token's nbf (not-before) sits in your future and validators reject it. Our lab issued a token with nbf 300 seconds ahead; the API returned 401 invalid_token with "Token not yet valid (nbf)".

The client cannot fix a skewed issuer. What it can do: allow a small leeway (30–60 seconds) when validating, sync its own clock via NTP, and log the nbf/exp values when this error appears.

If every fresh token fails this way, the issuer's clock is the bug — report it with timestamps.

Our Lab Reproduction

Stack: Python 3.13.5 mock OAuth API on localhost, tested 2 Dec 2026. Access tokens lived 6 seconds; refresh tokens rotated on every use.

We measured: fresh token 200, expired token 401, refresh then retry 200, reused refresh token 400 invalid_grant, proactive refresh with zero 401s, and a future-nbf token 401.

Honest lab note: the mock implements the RFC 6749/6750 shapes, not any specific provider. Real providers add quirks — some return 401 instead of 400 for invalid_grant, some allow a grace window for the previous refresh token.

The patterns transfer; the exact status codes deserve one test against your provider.

The Fix, Step by Step

  1. Store expires_in with the token. Compute a refresh deadline at 80% of the lifetime.
  2. Before each request, refresh if past the deadline. Share one in-flight refresh across threads or tabs (single-flight).
  3. On a 401 with error="invalid_token", refresh once and retry once. Log the WWW-Authenticate value when it happens.
  4. Persist the new refresh token immediately and atomically. Never keep two generations "just in case" — that is what reuse detection punishes.
  5. On invalid_grant, stop refreshing. Send the user through a fresh login; the session is over.
  6. Add small clock leeway (30–60s) in validation and keep client clocks NTP-synced.

Minimal shape in Python (full client in Python Requests 401 Handling):

import time, requests

class TokenBox:
    def __init__(self, token_url):
        self.token_url = token_url
        self.access = None
        self.refresh = None
        self.deadline = 0

    def ensure(self):
        if time.time() < self.deadline:
            return self.access
        r = requests.post(self.token_url, data={
            "grant_type": "refresh_token",
            "refresh_token": self.refresh,
        })
        r.raise_for_status()
        body = r.json()
        self.access = body["access_token"]
        self.refresh = body["refresh_token"]  # rotation: always replace
        self.deadline = time.time() + body["expires_in"] * 0.8
        return self.access

What Did Not Work

Retrying the same expired token three times produced three identical 401s in our lab. Retries without new credentials are just load. The token does not heal.

Refreshing on every request also fails the design goal: it multiplies token-endpoint traffic and, with rotation, multiplies the chance of a race. Refresh on a schedule derived from expires_in, not per call.

Keeping the old refresh token as a fallback after rotation backfired in the lab: presenting it returned invalid_grant. With reuse detection in production, that same move can revoke the entire session family.

Prevention

Treat token lifetime as part of your API contract: publish expires_in, honor it on the client, and alert on refresh-failure rates. Test the expiry path in CI with short-lived tokens, the same trick this lab used.

Review the OAuth side in OAuth 401 Refresh Token Errors and the header details in Authorization Header Hygiene.

FAQ

Should I refresh proactively or wait for a 401? Proactively, at about 80% of the lifetime.

It avoids the failed request entirely. Keep the reactive path as a safety net for tokens that expire early or get revoked.

Why did my refresh token stop working after one use? Rotation.

The server issued a new refresh token with the last exchange and retired the old one. Always store and use the newest refresh token; reusing a retired one returns invalid_grant.

Is a failed refresh a 401 or a 400? Per RFC 6749, token endpoint errors such as invalid_grant are 400.

Some providers use 401 anyway. Handle both, and key your logic on the error value, not only the status.

What is clock skew and why does it cause 401? If the issuer's clock is ahead of the validator's, fresh tokens look not-yet-valid (nbf in the future).

Allow 30–60 seconds of leeway and keep clocks NTP-synced. Persistent failures on fresh tokens mean the issuer clock needs fixing.

Two tabs refreshed at the same time and I got logged out. Why? Both presented the same refresh token; rotation retired it on the first exchange, and reuse detection treated the second as theft. Make refresh single-flight across tabs and processes.

Sources and Date

Lab tests run 2 Dec 2026 on Python 3.13.5 (mock OAuth API, localhost, 6-second token TTL). Captures are from that run with token values shortened. References verified live on 2 Dec 2026.

References

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


More posts