Reproducing Authentication Errors Your Devs Can Actually Fix
"Auth is broken" is one of the least useful bug reports a developer can receive. So is a CI log that says 401 Unauthorized and nothing else. Authentication failures are frustrating because the evidence disappears quickly: tokens expire, sessions rotate, and by the time someone looks, the request that failed can't be replayed.
What developers can fix is a reproduction: a specific request, sent with a specific kind of credential, that fails the same way every time. In practice, the work of turning an auth failure into that reproduction is mostly about capturing the right details at the moment of failure and leaving out the secrets.
This matters more now that AI agents call APIs too. An agent working through a tool or an MCP server authenticates with its own token and scopes, and when it gets a 401 or 403, it often reports something vague or simply tries something else. In this article I'll cover what to capture, how to reproduce role and scope mismatches without real user accounts, how to make auth tests useful in CI, and how the same approach applies to agents.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Capture the token state, not the token
The first thing a developer needs to know is which kind of credential failed and why the server might have rejected it. That's almost always visible in the token's claims and the response headers, without sharing the token itself.
For JWT access tokens, I decode the claims locally without verifying the signature. That's fine for diagnosis, never for authorisation decisions:
import time
import jwt # PyJWT
def describe_token(token):
claims = jwt.decode(token, options={"verify_signature": False})
now = int(time.time())
return {
"iss": claims.get("iss"),
"aud": claims.get("aud"),
"sub_present": "sub" in claims,
"scope": claims.get("scope"),
"exp_in_seconds": claims.get("exp", 0) - now,
"iat_age_seconds": now - claims.get("iat", now),
}
That summary answers the common questions straight away. Is it expired, or about to be? Is the audience the one this API expects? Was it issued by the right environment's identity provider? Does it carry the scope the endpoint needs? A negative exp_in_seconds on a token you just fetched points at clock skew between machines, which is a very different fix from a bad scope.
Also capture the response. Many APIs using bearer tokens return a WWW-Authenticate header on a 401 with an error such as invalid_token, and sometimes a description. That header is often more precise than the body. Record the method, the path, the request id or correlation header if the API returns one, and the timestamp, so a developer can find the server-side log entry.
What not to capture: the raw token, refresh tokens, client secrets or full cookie headers. Redact them in your test logging so they never reach CI output or a bug tracker. My notes on keeping test secrets out of version control cover the storage side.
401 or 403: say which, and why
The distinction tells a developer where to look. A 401 means the request wasn't authenticated: no credential, an expired or malformed one, or one the server couldn't verify. A 403 means the server knows who you are and has decided you can't do this. Treating them as interchangeable sends people to the wrong code.
A good auth bug report states which one happened, the decoded claims that matter, and the expectation: "a token with scope orders:write for tenant A should be able to create an order for tenant A; it receives 403." If you see 401s that come and go, the cause is often something other than credentials. I've written separately about intermittent 401s that aren't actually auth failures.
Reproduce role and scope mismatches with test identities
You don't need a real person's account to reproduce a permission bug. Most identity setups let you issue tokens for test clients or test users with specific roles and scopes. Build a fixture that requests a token with exactly the scopes a scenario needs, and the reproduction becomes a test:
import pytest
import requests
@pytest.mark.parametrize("scopes, expected_status", [
(["orders:read"], 403),
(["orders:read", "orders:write"], 201),
([], 403),
])
def test_create_order_requires_write_scope(token_for, api_base_url, scopes, expected_status):
token = token_for(scopes=scopes)
response = requests.post(
f"{api_base_url}/orders",
json={"sku": "QA-001", "quantity": 1},
headers={"Authorization": f"Bearer {token}"},
timeout=10,
)
assert response.status_code == expected_status, response.text
Here token_for is your own fixture that talks to your identity provider's test setup. A developer can run that test, see it fail, fix the policy and see it pass. That's a reproduction they trust, because it doesn't depend on anyone's account or on a token pasted into a ticket.
Make auth tests useful in CI
Auth tests can get slow and noisy if every test fetches a new token. A few habits keep them useful:
- Cache tokens per scope set for the session, and refresh them before expiry rather than on failure.
- On any 401 or 403, log the
describe_tokensummary and theWWW-Authenticateheader automatically, so a failing CI run already contains the diagnosis. - Keep a small, explicit set of negative auth tests: missing token, expired token, wrong audience, missing scope. Run them on every change.
Token expiry across environments deserves its own attention, since a token valid in one environment may be rejected in another. See diagnosing token expiry failures across test environments.
When the caller is an AI agent
Agents now call APIs through tools, often an MCP server or a thin wrapper that holds a credential on the agent's behalf. Auth failures there are harder to read, because the agent sits between you and the response. An agent that gets a 403 may report "I couldn't complete the task", retry with different parameters, or try another tool entirely. None of that tells a developer what failed.
The approach is the same one as above, applied at the tool layer:
- Log at the tool boundary. The wrapper that makes the HTTP call should record status, the token summary (never the token), the scopes and the request id. That log, not the agent's explanation, is the evidence.
- Return a structured error to the agent. "403: missing scope orders:write" lets the agent stop and report accurately instead of guessing.
- Test the scope boundaries directly. Give the agent's tool credential the narrowest scopes it needs, and write tests that confirm a call outside them gets a 403. That's a security check, not just a functional one: an agent that can be talked into calling an endpoint should still be refused by the API.
- Keep secrets out of prompts. When you ask an AI assistant to help debug an auth failure, give it the decoded claims summary and headers, not the token. Anything pasted into a prompt should be treated as shared.
The goal is a repro, not a report
The developer-friendly auth bug is a test that fails for a stated reason, using test identities and redacted evidence. Whether the caller was your suite, a teammate or an agent, the recipe is the same. If you want a structured way to build API suites that handle auth this cleanly in Python or Node, my API testing courses cover it with VS Code and GitHub Copilot.