401 Unauthorized with JWT/Bearer Tokens: Causes and Fixes

401 Unauthorized with JWT/Bearer Tokens: Causes and Fixes

Written by

in

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

Fix Box — Try This First (10 Seconds)

A Bearer 401 means the server rejected your token, not your password. First, read the WWW-Authenticate header — it names the exact failure.

Second, if it says invalid_token and "expired", refresh the token; retrying the same token never works. Third, check the format: exactly Authorization: Bearer <token>, one space, no quotes.

Still stuck? Run the 401 Checker on your endpoint, or start from the pillar guide 401 Unauthorized: Causes and How to Fix It.

Table of Contents

What the Server Is Actually Saying

A 401 is an authentication challenge, not a permission verdict. The server is saying: "I do not accept the credentials on this request." It must also send a WWW-Authenticate header that describes what it expects instead.

That header is your diagnosis, printed for free on every failed request. Most developers never read it.

They retry, rotate secrets at random, or blame the framework. Read the header first and the cause is usually obvious.

Per RFC 9110, a 401 response must include at least one challenge. For Bearer tokens, RFC 6750 defines the error codes invalid_request, invalid_token, and insufficient_scope.

Each code points at a different fix. invalid_request means your request is malformed.

invalid_token means the token itself is expired, revoked, or invalid. Confusing the two wastes hours.

The Exact Messages (Verbatim from Our Lab)

We reproduced all four Bearer failures against a local mock API on 2 Dec 2026. These are the real response headers our lab captured, sanitized of lab-only token values:

HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api"
{"error": "missing_token", "error_description": "Authorization header missing"}
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token", error_description="The access token expired"
{"error": "invalid_token", "error_description": "The access token expired"}
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_request", error_description="Authorization scheme must be Bearer"
{"error": "invalid_request", "error_description": "Authorization scheme must be Bearer"}

Search for your exact error_description text when you are stuck. It is far more specific than the status code alone. Two APIs can both return 401 for opposite reasons.

Cause 1: Expired Token

JWTs carry an exp claim, and servers reject them after it passes. This is the most common Bearer 401 in production.

The token looks fine, decodes fine, and worked yesterday. The clock simply ran out.

Our lab reproduced it with a token whose exp was set in the past. The server answered invalid_token with "The access token expired" every single time.

The fix is a refresh flow, not a retry. Use your refresh token to get a new access token, then resend the original request once.

If you have no refresh token, send the user through login again. Never loop retries with the same expired token. We tested that in the lab: two retries, two identical 401s, zero progress.

Cause 2: Missing Authorization Header

Sometimes the header never arrives. A proxy strips it, a redirect drops it, or the client code forgets to attach it.

Our lab case 1 sent no header at all. The server replied with a bare challenge, Bearer realm="api", and no error code. A bare challenge usually means "no credentials were presented."

Check redirects first. Many HTTP clients drop Authorization when following a cross-host redirect, by design.

Also check your framework: some servers need explicit configuration to pass the header through to the application. On Apache with CGI/FastCGI, Authorization is famously not forwarded unless configured.

Cause 3: Wrong Scheme or Malformed Header

The scheme word must be Bearer, followed by one space, followed by the token. Our lab sent Authorization: Token <valid-token> instead.

The server rejected it as invalid_request even though the token itself was valid. Common variants: Bearer with no token, token wrapped in quotes, token pasted with a trailing newline, or the raw token with no scheme at all.

We also tested a lowercase bearer scheme. Our strict lab server rejected it as invalid_request.

In theory the scheme is case-insensitive, and many real servers accept lowercase. Do not rely on that. Send exactly Bearer and remove one variable from your debugging.

Cause 4: Invalid or Revoked Token

A token can be well-formed and still rejected. Wrong signing key, wrong issuer, wrong audience, or a token revoked server-side.

Our lab case 4 sent a garbage token and got invalid_token with "The access token is invalid." Notice how close that is to the expired message. The error code is the same; only the description differs.

If fresh tokens also fail, compare issuer and audience claims against what the API expects. Then check clock skew between client and server. A server clock minutes ahead makes brand-new tokens look expired.

Our Lab Reproduction

Stack: Python 3.13.5, http.server mock API on localhost, tested 2 Dec 2026. The mock validates three token states: valid, expired, and unknown.

It returns RFC 6750-style challenges for each failure. Clients tested: curl and Python urllib. Full captured output is stored with this package as lab evidence.

Before the fix, every failure mode returned 401 with a distinct challenge. After the fix — correct scheme, valid unexpired token — the same endpoint returned 200 OK with the payload. The before/after pair below is verbatim lab output, with only the lab token value removed:

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

# AFTER (refreshed token)
HTTP/1.0 200 OK
{"ok": true, "data": "lab payload"}

Honest lab note: this is a local mock that mirrors RFC 6750 challenge behavior. It proves the client-side diagnosis flow, not any specific vendor's exact wording.

Real APIs vary in error_description text. The error codes and the fix sequence are the portable part.

The Fix, Step by Step

  1. Reproduce with curl and read the challenge header:
curl -si https://your-api.example/data
curl -si -H "Authorization: Bearer YOUR_TOKEN" https://your-api.example/data
  1. Match the error code. invalid_request means fix the header format. invalid_token plus "expired" means refresh. invalid_token on a fresh token means check issuer, audience, signing key, and clock skew.
  2. Implement refresh-once logic in the client. This Python pattern is the one we tested in the lab:
import urllib.request, urllib.error

def call(url, token):
    req = urllib.request.Request(url, headers={"Authorization": "Bearer " + token})
    try:
        with urllib.request.urlopen(req) as r:
            return r.status, r.read().decode()
    except urllib.error.HTTPError as e:
        return e.code, e.headers.get("WWW-Authenticate")

status, challenge = call("https://your-api.example/data", access_token)
if status == 401:
    access_token = refresh_access_token()  # your OAuth refresh call
    status, _ = call("https://your-api.example/data", access_token)
  1. Verify the fix returns 200, then log the challenge header (never the token) on future 401s.

What Did Not Work

Retrying the expired token unchanged failed twice in our lab, identically. A 401 with invalid_token will not heal itself. Waiting does not help either; expiry only gets worse.

Sending the token as a query parameter (?access_token=...) also failed in our lab.

The server only reads the header, so it answered as if no credentials were sent. Query-string tokens also leak into logs and browser history. RFC 6750 allows them only as a last resort; avoid them.

Lowercase bearer failed against our strict lab server. Some production servers accept it, many do not. It is a needless gamble when Bearer costs nothing.

Prevention

Refresh proactively at 80% of token lifetime instead of waiting for a 401. Log WWW-Authenticate on every auth failure, with the token itself redacted.

Add a smoke test that calls one protected endpoint with a real token after every deploy. For the full decision flow across all auth types, see the pillar 401 Unauthorized: Causes and How to Fix It and the 401 Checker.

Related: 401 Invalid API Key Errors and 401 Basic Auth Failures.

FAQ

Why do I get 401 with a token that worked yesterday? Almost certainly expiry.

Decode the JWT and compare its exp claim with the current time. Then refresh instead of retrying.

What is the difference between 401 and 403 with tokens? 401 means the credentials were not accepted at all.

403 means they were accepted but lack permission for this action. A valid token with the wrong scope is a 403 case on many APIs, though some return 401 with insufficient_scope.

Can I send the token without the word Bearer? No.

The scheme is part of the header format. Our lab rejected a bare token and a Token scheme, both as invalid_request.

Why does it work in Postman but fail in my code? Compare the raw headers.

Code often adds quotes, trailing whitespace, or a stale token from config. Print the header name and scheme (never the full token) and diff it against the working request.

Should I retry a 401 automatically? Only after refreshing the token, and only once. Blind retries with the same token just repeat the same rejection, as our lab showed.

Sources and Date

Lab tests run 2 Dec 2026 on Python 3.13.5 (mock API, localhost). Header captures in this article are from that run, sanitized of lab token values. Standards 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