Lab-tested: Python 3.13.5 mock OAuth server (lab) · 2 Dec 2026 · Every failure below reproduced before it was written
Fix Box — Try This First (10 Seconds)
An OAuth 401 usually means your access token died and the refresh path is broken too. First, read the error: invalid_token on the resource means refresh once.
Second, if refresh returns invalid_grant, the refresh token is dead — stop retrying and send the user through login again. Third, if the challenge says insufficient_scope, the token is fine but lacks a scope; re-authorize with that scope.
Still stuck? Walk the 401 Decision Tree or start from the pillar 401 Unauthorized: Causes and How to Fix It.
Table of Contents
- Two Endpoints, Two Different Failures
- The Exact Messages (Verbatim from Our Lab)
- Cause 1: Access Token Expired, Refresh Works
- Cause 2: Refresh Token Expired or Revoked (invalid_grant)
- Cause 3: Refresh Token Reuse and Family Revocation
- Cause 4: Insufficient Scope
- Cause 5: Consent Revoked by the User
- Cause 6: Client Authentication Failed at the Token Endpoint
- Our Lab Reproduction
- The Fix, Step by Step
- What Did Not Work
- Prevention
- FAQ
- Sources and Date
- References
Two Endpoints, Two Different Failures
OAuth splits the failure across two endpoints, and that split confuses everyone. The resource server returns 401 when the access token is rejected.
The token endpoint returns 400 with invalid_grant when the refresh token is dead, and 401 with invalid_client when the client itself fails to authenticate. Three different responses, three different fixes.
Per RFC 6749 Section 5.2, token endpoint errors are JSON with an error code. Per RFC 6750 Section 3.1, resource errors travel in the WWW-Authenticate challenge.
Read both places. The resource challenge tells you the access token is bad; the token endpoint response tells you whether refreshing can save you.
The Exact Messages (Verbatim from Our Lab)
We reproduced the full OAuth failure set against a local mock authorization server on 2 Dec 2026. These are the real responses our lab captured, sanitized of lab-only token values:
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token", error_description="The access token is invalid or revoked"
{"error": "invalid_token", "error_description": "The access token is invalid or revoked"}
HTTP/1.0 400 Bad Request
{"error": "invalid_grant", "error_description": "Refresh token expired or revoked"}
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api", scope="write", error="insufficient_scope", error_description="Token scope does not include write"
{"error": "insufficient_scope", "error_description": "Token scope does not include write"}
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Basic realm="oauth-token"
{"error": "invalid_client", "error_description": "Client authentication failed"}
Search for your exact error value when you are stuck. invalid_grant and invalid_token look similar and mean opposite things. One is fixed by refreshing; the other means refreshing is impossible.
Cause 1: Access Token Expired, Refresh Works
Access tokens are short-lived on purpose. When one expires, the resource returns 401 invalid_token, and the correct move is a single refresh.
Our lab case 1 started with a revoked access token and got exactly that 401. Case 2 refreshed successfully, and case 3 called the resource with the new token and got 200 OK.
The pattern is: catch the 401, refresh once, resend the original request once. Never loop.
If the refreshed token also fails, the problem is not expiry. Log the challenge header (never the token) and move to the causes below.
Cause 2: Refresh Token Expired or Revoked (invalid_grant)
Refresh tokens also die: absolute lifetime, inactivity timeout, password change, or admin revocation. The token endpoint answers 400 with invalid_grant, as our lab case 4 shows.
This is not a 401, and that is the point — the refresh path itself is closed.
There is no retry fix for invalid_grant. The user must go through the authorization flow again.
Clients that loop on invalid_grant just hammer the token endpoint. Treat it as a terminal state: clear stored tokens, restart login.
Cause 3: Refresh Token Reuse and Family Revocation
Modern providers rotate refresh tokens: every refresh issues a new one and invalidates the old. If an old token shows up again, the provider assumes theft and revokes the entire token family.
Our lab reproduced this in cases 5 and 6. Reusing the rotated token returned invalid_grant with "reuse detected", and afterwards even the newest refresh token in that family was dead.
The usual cause is a race: two app instances refreshing at the same time with the same stored token. One wins, the other presents a dead token and triggers family revocation.
Fix it with a refresh lock: only one process refreshes, everyone else waits and reuses the result. Also persist the new refresh token immediately, before using the new access token.
Cause 4: Insufficient Scope
Sometimes the token is valid and still rejected. The challenge carries error="insufficient_scope" and a scope attribute naming what is required, as in our lab case 7. Refreshing does not help; the refreshed token carries the same scopes.
The fix is re-authorization with the missing scope added. Send the user through consent again with the expanded scope list.
On some providers this same situation returns 403 instead of 401. Read the challenge either way; it names the scope you lack.
Cause 5: Consent Revoked by the User
Users can revoke your app's access from their account settings. The provider then kills the access token, and often the refresh token too.
Our lab case 8 simulated a server-side revoked access token: 401 invalid_token, identical to expiry at first glance.
The difference shows up at refresh time. If refresh also returns invalid_grant, consent is gone or the grant was revoked.
Only a fresh authorization flow restores access. Do not nag the user in a loop; one clean re-login prompt is the correct behavior.
Cause 6: Client Authentication Failed at the Token Endpoint
Confidential clients must authenticate to the token endpoint, usually with HTTP Basic client credentials. Forget them and you get 401 invalid_client with a Basic challenge, as in our lab case 9.
Note the scheme: this 401 is about your app's credentials, not the user's token.
Check that the client secret matches the environment you are calling. A staging secret against production fails exactly like this.
Also confirm the grant type: our lab case 10 sent grant_type=password to a refresh-only endpoint and got unsupported_grant_type. Small form mistakes produce very different errors; read the JSON body.
Our Lab Reproduction
Stack: Python 3.13.5 mock OAuth authorization and resource server on localhost, tested 2 Dec 2026. The mock implements the refresh grant with rotation and reuse detection, client Basic authentication, scope checks, and server-side revocation.
Clients tested: curl. Full captured output is stored with this package as lab evidence (11 cases).
The before/after pair below is verbatim lab output, with only lab token values removed:
# BEFORE (revoked access token on resource)
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token", error_description="The access token is invalid or revoked"
# AFTER (refresh grant, then new access token)
HTTP/1.0 200 OK
{"access_token": "<new>", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "<rotated>", "scope": "read write"}
HTTP/1.0 200 OK
{"ok": true, "data": "lab payload", "scope": "read write"}
Honest lab note: this is a local mock that mirrors RFC 6749 and RFC 6750 behavior, including rotation with reuse detection. It proves the client-side diagnosis and recovery flow, not any specific provider's exact wording or lifetimes.
Real providers vary in refresh token lifetimes and in whether reuse revokes the family. The error codes and the fix sequence are the portable part.
The Fix, Step by Step
- Capture both responses. The resource 401 challenge and the token endpoint JSON:
curl -si -H "Authorization: Bearer YOUR_ACCESS_TOKEN" https://your-api.example/data
curl -si -X POST https://your-provider.example/oauth/token \
-u "CLIENT_ID:CLIENT_SECRET" \
-d "grant_type=refresh_token&refresh_token=YOUR_REFRESH_TOKEN"
- Match the error.
invalid_tokenmeans refresh once.invalid_grantmeans full re-login.insufficient_scopemeans re-authorize with the named scope.invalid_clientmeans fix your app credentials. - Implement refresh with a lock and immediate persistence. This is the pattern our lab validated:
import threading
refresh_lock = threading.Lock()
def get_access_token(store, refresh_call):
with refresh_lock: # one refresher at a time; prevents reuse races
tokens = refresh_call(store["refresh_token"])
if tokens.get("error") == "invalid_grant":
store.clear()
raise NeedsLogin("refresh token dead; restart authorization flow")
store["refresh_token"] = tokens["refresh_token"] # persist FIRST
store["access_token"] = tokens["access_token"]
return tokens["access_token"]
- Verify: the original request returns 200 with the new token, and the stored refresh token is the rotated one.
What Did Not Work
Retrying the refresh after invalid_grant failed identically in our lab. A dead refresh token does not heal. Every retry is wasted load and, with rotation providers, can look like abuse.
Reusing the previous refresh token after a successful rotation failed harder: it revoked the whole token family in our lab, killing even the newest token. This is why the refresh lock and immediate persistence matter.
Two tabs or two workers refreshing concurrently is the classic trigger.
Refreshing to fix insufficient_scope also did nothing. The new token carried the same scopes and the resource rejected it the same way. Scope problems are consent problems, not token problems.
Prevention
Refresh proactively at 80% of access token lifetime, under a lock, and persist rotated refresh tokens before anything else. Treat invalid_grant as terminal: clear tokens, restart login, never loop.
Log the error code from both endpoints on every failure, with token values redacted. For the full cross-scheme flow see the pillar 401 Unauthorized: Causes and How to Fix It and the 401 Decision Tree.
Related: 401 JWT/Bearer Token Errors and 401 Checker.
FAQ
Why do I get 401 after refreshing successfully? Check scope first: the new token may lack the required scope (insufficient_scope). Then check that you actually sent the new token, not a cached copy of the old one.
What is the difference between invalid_token and invalid_grant? invalid_token is the resource rejecting your access token; refresh can fix it. invalid_grant is the token endpoint rejecting your refresh token; only a new login fixes it.
Why did all my tokens die at once? Probably refresh token reuse.
With rotation, presenting an old refresh token can revoke the whole family. Add a refresh lock and persist the rotated token immediately.
Can I refresh without client credentials? Public clients (mobile, SPA) use PKCE and no secret; confidential clients must authenticate. A 401 invalid_client means your client authentication failed, not the user's.
How long do refresh tokens live? It varies by provider: hours to months, often with inactivity timeouts. Plan for invalid_grant as a normal event, not an exception.
Sources and Date
Lab tests run 2 Dec 2026 on Python 3.13.5 (mock OAuth server, localhost). Header and body captures in this article are from that run, sanitized of lab token values. Standards references verified live on 2 Dec 2026.
References
- RFC 6749, The OAuth 2.0 Authorization Framework, Section 5.2 (error response) and Section 6 (refreshing): https://www.rfc-editor.org/rfc/rfc6749.html
- RFC 6750, OAuth 2.0 Bearer Token Usage, Section 3.1 (error codes): https://www.rfc-editor.org/rfc/rfc6750.html
- RFC 9110, HTTP Semantics, Section 15.5.2 (401 Unauthorized): https://www.rfc-editor.org/rfc/rfc9110.html
- MDN Web Docs, 401 Unauthorized: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401
- MDN Web Docs, WWW-Authenticate: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate






Leave a Reply