Python Requests 401 Handling: Refresh Once, Retry Once

Python Requests 401 Handling: Refresh Once, Retry Once

Written by

in

Lab-tested: Python 3.13.5 + requests 2.34.2 · 2 Dec 2026 · Reproduced and fixed in our lab

Fix Box — Try This First (10 Seconds)

Never retry a 401 with the same token — it will fail identically. Read WWW-Authenticate from the response, refresh the token once, and retry the request once.

In requests, the clean way is a Session with a custom AuthBase class that hooks the response. Start from the pillar 401 Unauthorized: Causes and How to Fix It and the lifecycle rules in Prevent 401: Token Refresh Done Right.

Table of Contents

Why Naive Retries Fail

A 401 is deterministic: same credentials, same answer. Retry loops, exponential backoff, and urllib3 retry adapters all resend the identical Authorization header.

The server refuses it identically, three times, while your logs fill with noise and the API rate-limits you for the privilege.

The only retry that can succeed is one carrying different credentials. That means the retry logic must be credential-aware: on 401, obtain a fresh token, then replay the request once. Everything in this article follows from that one rule.

The Exact Responses (Verbatim from Our Lab)

Our lab ran Python 3.13.5 with requests 2.34.2 against a mock OAuth API issuing 6-second tokens. The naive loop and the smart session, captured 2 Dec 2026:

N1 naive retry 1 same expired token: HTTP 401 ... error="invalid_token", error_description="The access token expired"
N2 naive retry 2 same expired token: HTTP 401 ... error="invalid_token", error_description="The access token expired"
N3 naive retry 3 same expired token: HTTP 401 ... error="invalid_token", error_description="The access token expired"
  hook saw 401, challenge: Bearer realm="api", error="invalid_token", error_description="The access token expired"
S1 smart session: 401 -> refresh once -> retry: HTTP 200

Three retries bought three identical refusals. One refresh bought a 200. The difference is not persistence; it is changing the credential.

Reading WWW-Authenticate in Code

The response header tells you which failure you have. requests exposes it as r.headers.get("WWW-Authenticate").

Branch on the error value: invalid_token means refresh or re-login; invalid_request means your header construction is broken (see Authorization Header Hygiene); insufficient_scope arrives with 403 and means stop — refreshing cannot add scope.

Parse defensively. The header may be absent (some APIs send bare 401s), parameters may be quoted or bare, and multiple challenges can share one header. A tiny parser that extracts error="..." with a regex covers the common cases; treat a missing header as "unknown — log the body."

import re

def challenge_error(resp):
    header = resp.headers.get("WWW-Authenticate", "")
    m = re.search(r'error="([^"]+)"', header)
    return m.group(1) if m else None

Pattern 1: Manual Refresh-and-Retry

For scripts and one-off jobs, an explicit helper is clearest. It sends the request, and on 401 refreshes and retries exactly once:

import requests

def call_with_refresh(session, method, url, token_box, **kw):
    resp = session.request(method, url, **kw)
    if resp.status_code != 401:
        return resp
    if challenge_error(resp) not in (None, "invalid_token"):
        return resp  # malformed header etc.: refreshing will not help
    token_box.refresh()  # updates session auth with the new token
    return session.request(method, url, **kw)  # retry once, then stop

The retry-once cap is deliberate. If the refreshed token also gets 401, the problem is not expiry — it is revocation, scope, or a broken header. Surface that response instead of looping.

Pattern 2: Session + AuthBase Hook

For long-lived clients, hide the logic in an AuthBase subclass. It stamps the current token on every request and registers a response hook that refreshes and replays on 401. This is the exact class our lab ran:

import requests

class RefreshAuth(requests.auth.AuthBase):
    def __init__(self, access_token, refresh_token, token_url):
        self.access = access_token
        self.refresh_token = refresh_token
        self.token_url = token_url

    def __call__(self, r):
        r.headers["Authorization"] = f"Bearer {self.access}"
        r.register_hook("response", self.handle_401)
        return r

    def handle_401(self, r, **kw):
        if r.status_code != 401:
            return r
        nr = requests.post(self.token_url, data={
            "grant_type": "refresh_token",
            "refresh_token": self.refresh_token,
        })
        if nr.status_code != 200:
            return r  # session is over; surface the original 401
        body = nr.json()
        self.access = body["access_token"]
        self.refresh_token = body["refresh_token"]  # rotation: replace
        req = r.request.copy()
        req.headers["Authorization"] = f"Bearer {self.access}"
        return r.connection.send(req, **kw)

session = requests.Session()
session.auth = RefreshAuth(access, refresh, "https://auth.example/oauth/token")
resp = session.get("https://api.example/data")  # 401 -> refresh -> 200

Two details matter. The hook replays the prepared request with the new header — body included — so POSTs survive the retry.

And with rotating refresh tokens, self.refresh_token must be replaced on every exchange, or the next refresh earns invalid_grant.

Pattern 3: Proactive Refresh with Expiry Tracking

Reactive handling wastes one round trip per expiry. Track expires_in and refresh before the deadline instead — at 80% of the lifetime. Combine both: proactive refresh as the norm, the 401 hook as the safety net for early revocation.

import time

class TokenBox:
    def __init__(self, token_url):
        self.token_url = token_url
        self.access = None
        self.refresh_token = None
        self.deadline = 0.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_token,
        })
        r.raise_for_status()
        body = r.json()
        self.access = body["access_token"]
        self.refresh_token = body["refresh_token"]
        self.deadline = time.time() + body["expires_in"] * 0.8
        return self.access

Guard the refresh with a lock in threaded code. Two threads refreshing with the same rotating token race, and the loser presents a retired token — the exact false-theft signal described in Prevent 401: Token Refresh Done Right.

Our Lab Reproduction

Stack: Python 3.13.5, requests 2.34.2, mock OAuth API with 6-second access tokens and rotating refresh tokens, tested 2 Dec 2026. Measured: three naive retries with an expired token returned three identical 401s; the RefreshAuth session converted the same situation into one refresh plus a 200; the hook correctly read the invalid_token challenge before refreshing.

Honest lab note: the mock follows RFC 6749/6750 shapes. Real providers differ in error bodies and sometimes in status codes for refresh failures. The patterns hold; test the challenge_error branching against your provider's actual responses before shipping.

The Fix, Step by Step

  1. Reproduce once with a plain call and print status_code, WWW-Authenticate, and the body. Confirm you have invalid_token, not a header bug.
  2. Implement refresh as a single function that updates both tokens atomically. Replace the refresh token every time (rotation).
  3. Wire it reactively first (Pattern 1 or 2): 401 → refresh → retry once → return whatever comes back.
  4. Add proactive refresh (Pattern 3) with an 80% deadline and a lock around the refresh call.
  5. Log every refresh and every final 401 with the challenge error value. Never log token values — length and last four characters only.
  6. Test with short-lived tokens in staging. If expiry is not exercised in tests, it will be exercised in production.

What Did Not Work

urllib3 retry adapters with status_forcelist=[401] did not work: they resend the same header, so the retry is a photocopy of the failure. Retries fix transient network errors, not credential errors.

Catching HTTPError from raise_for_status() and retrying the whole block without refreshing failed the same way. The exception path must change the credential, or it changes nothing.

Refreshing inside every request function separately caused double refreshes under concurrency in design review: two callers, one rotating token, one invalid_grant. Centralize refresh behind one lock and one token store.

Prevention

Treat token handling as shared infrastructure: one TokenBox, one lock, one place that builds the Authorization header. Alert on refresh failures and on final 401s by error value.

For the server-side view of the same errors, see OAuth 401 Refresh Token Errors and the 401 Checker for endpoint-level tests.

FAQ

Should I use raise_for_status() with 401 handling? Yes, but catch the 401 before it raises, or check status_code first. The hook pattern handles the response before raise_for_status() sees it, which keeps call sites clean.

How many times should I retry after a 401? Once, after a successful refresh.

A second 401 means the new credential was also refused — revocation, scope, or a malformed header. More retries only add load.

What if the refresh itself returns 401? Some providers answer token-endpoint failures with 401 instead of the RFC 6749 400 invalid_grant. Either way, the session is over: stop refreshing and send the user through a fresh login.

Can I replay a POST after a 401? Yes, if the request is safe to repeat.

The hook replays the prepared request including its body. For non-idempotent operations, confirm the first attempt truly failed with 401 (it was refused before processing) — a 401 means the server did not apply it.

Where should tokens live in a requests app? In one token store object, loaded from environment or a secret manager, never hardcoded and never logged. Persist rotating refresh tokens atomically so a crash cannot leave you holding a retired token.

Sources and Date

Lab tests run 2 Dec 2026 on Python 3.13.5 with requests 2.34.2 against a local mock OAuth API (6-second token TTL). Captures are from that run with token values removed. 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