When an API returns 401 or 403 even though a JWT appears valid, the failure is usually caused by a mismatch between what the client sends, what the issuer signs, and what the API or gateway expects. This guide provides a repeatable troubleshooting workflow for inspecting token structure, claims, signatures, scopes, cookies, CORS, and intermediary behavior without exposing credentials or weakening production security.
Overview
Authentication and authorization failures can look deceptively similar. A 401 Unauthorized response usually means the service could not accept the presented credentials: the token may be missing, malformed, expired, incorrectly signed, or issued for another service. A 403 Forbidden response commonly means the request was identified but does not have sufficient permission for the requested resource. These conventions are useful diagnostics, not absolute rules; gateways and application frameworks may apply their own response behavior.
Start by locating the first component that rejects the request. A typical request may pass through a browser or mobile client, a CDN or API gateway, an identity-aware proxy, a service mesh, and finally the application. Any layer can validate a token, remove an authorization header, translate an error, or enforce a separate policy. Comparing the response from the public endpoint with a direct request to the service, where that is safe and possible, can reveal whether the problem begins at the edge or inside the application.
| Response or symptom | Initial questions |
|---|---|
| 401 with no token | Did the client attach the expected Authorization header or cookie? |
| 401 with a token | Is the token parseable, unexpired, correctly signed, and intended for this API? |
| 403 with a valid token | Does the token contain the required scope, role, tenant, or resource permission? |
| Works in a script but not in a browser | Are CORS, cookie attributes, preflight requests, or frontend configuration involved? |
| Works directly but fails through a gateway | Is the gateway forwarding the credential and preserving the relevant claims? |
Record the request path, method, environment, response status, correlation ID, and authentication mode before changing configuration. This creates a small evidence trail and prevents a successful test from hiding the original failure.
What to track
1. Token structure and transport
A signed JWT commonly has three base64url-encoded segments separated by periods: a header, a payload, and a signature. A token decoder or JSON formatter can help inspect a redacted development token, but decoding is not verification. Never paste a live production access token into an unapproved online utility, ticket, chat, or log system. Treat the token as a credential even when its payload is readable.
Confirm that the client sends the token in the format expected by the API, usually an Authorization header with the Bearer scheme, or in a cookie when the application is designed for cookie-based sessions. Check for accidental quotation marks, whitespace, line breaks, duplicated headers, and a token from the wrong environment. Also verify that a proxy, redirect, browser policy, or HTTP client is not stripping the credential.
2. Issuer, audience, and time claims
Compare the token claims with the API configuration. The iss claim identifies the issuer, while aud identifies the intended audience. An access token issued for a user-interface client, discovery endpoint, or different API may be genuine but still invalid for the resource server. Confirm exact values, including spelling, casing, URI formatting, and environment-specific hostnames.
Inspect exp, nbf, and, where used, iat. The expiration time must be in the past or future as appropriate to the claim. Small differences between the identity provider, gateway, container, and application clocks can cause boundary failures. Use controlled clock synchronization and a narrowly defined clock-skew tolerance rather than extending token lifetimes casually. If the error appears only near expiration, inspect refresh behavior and whether the client retries with the newly issued token.
3. Signature algorithm and key rotation
The JWT header identifies an algorithm and may include a key identifier such as kid. The verifier must allow the intended algorithm and obtain the corresponding public key from the configured issuer or key set. Do not solve an invalid-signature error by accepting arbitrary algorithms, disabling signature verification, or trusting an unverified header.
Key rotation introduces a timing and configuration checkpoint. If tokens signed with a new key fail while older tokens work, compare the token's kid with the verifier's available keys. Check key-set retrieval, caching, network access, issuer configuration, and whether the gateway and application have different key sources. A stale key cache can produce intermittent failures, especially when multiple instances refresh at different times.
4. Scopes, roles, and resource policy
After signature and claim validation succeed, authorization policy determines whether the request is allowed. Check the exact claim used by the application: it may be a space-delimited scope value, a roles claim, a group claim, a tenant identifier, or a resource-specific permission. Similar names do not guarantee equivalent meaning. A token with a broad identity claim may still lack the operation-specific permission required for a write, administrative action, or cross-tenant request.
Compare a successful request and a failing request using redacted claim names and values. Record the required permission for the route, the permission actually present, and the policy decision point that evaluated it. This is also a useful place to review least-privilege assumptions and access changes using the cloud IAM access review workflow.
5. Cookies, CORS, and browser behavior
Cookie-based authentication adds browser-specific variables. Review the cookie's domain, path, Secure setting, SameSite behavior, and expiration. Cross-site requests may also require an explicit frontend configuration and a server response that permits the intended origin and credentials. A preflight request can fail before the authenticated request is sent, while a missing cookie can produce a genuine 401.
CORS is not a replacement for authentication. It controls which browser origins may read responses; it does not make an API credential valid. Test browser failures with developer tools, inspect the preflight and actual request separately, and compare them with a controlled command-line request. Avoid using permissive origins or credential settings as a permanent troubleshooting shortcut.
6. Gateways, proxies, and service boundaries
Inspect each boundary for header forwarding, path rewriting, authentication plugins, and policy translation. A gateway may validate a token and pass only selected identity headers downstream, or it may expect the application to perform validation as well. Confirm whether the route uses the intended issuer, audience, scopes, and policy version. Correlation IDs and structured security logs should identify which component made the decision without recording the raw token.
Cadence and checkpoints
Authentication troubleshooting is most effective when the surrounding configuration is tracked rather than rediscovered during an incident. Review the following checkpoints monthly or quarterly, depending on the change rate and risk of the environment:
- Issuer and audience inventory: list each API, accepted issuer, audience, environment, and authentication method.
- Key and algorithm configuration: confirm approved algorithms, key-set endpoints, rotation procedures, cache behavior, and alert ownership.
- Authorization mappings: document routes or operations and the scopes, roles, tenant rules, or policies they require.
- Client flows: test login, refresh, logout, browser requests, service-to-service calls, and failure handling in a non-production environment.
- Gateway behavior: verify header forwarding, preflight handling, route policy, and error translation after proxy or identity changes.
- Logging hygiene: check that logs contain useful claim metadata and correlation IDs but not access tokens, cookies, passwords, or authorization headers.
Repeat these checks after an identity-provider change, API audience change, key rotation, gateway deployment, library upgrade, domain migration, or change to scopes and roles. Keep a known-good test request and a deliberately unauthorized test case so that changes can be compared consistently.
How to interpret changes
Look for the smallest change that explains the new failure. If every endpoint begins returning 401 at once, suspect issuer configuration, key retrieval, clock synchronization, or a gateway-wide header problem before investigating individual roles. If one route returns 403 while others work, inspect route policy, scopes, resource ownership, and tenant context. If only one user or client fails, compare its token issuance flow and claims with a known-good request.
Intermittent failures often indicate an inconsistent deployment or cache rather than a permanently invalid token. Compare instances, regions, gateway nodes, and key-set refresh times. A failure that follows a token across all instances points toward claims or signing; a failure that follows one instance points toward local configuration, stale keys, or clock drift.
When investigating an invalid signature, retain the token header and non-sensitive identifiers only in a controlled diagnostic record. For claim debugging, use a short-lived test token with synthetic identities and minimum privileges. Redact or hash identifiers where practical, and remove diagnostic artifacts after the investigation. If a production credential may have been exposed, stop using it and follow the organization's revocation and incident procedures rather than continuing to test with it.
For broader operational context, connect authentication errors with service health and deployment records. An increase in 401 or 403 responses may be an application release issue, an identity-provider dependency problem, or an intentional policy change. The SLO and alert threshold template can help define useful signals without paging on every isolated client error.
When to revisit
Revisit this guide on a monthly or quarterly review cycle and whenever an authentication dependency changes. The most important triggers are a new identity provider, issuer or audience update, signing-key rotation, algorithm change, gateway or service-mesh rollout, browser-domain change, cookie-policy change, authorization-model revision, or upgrade to a JWT, OAuth, API framework, or security library.
During a live incident, use this short checklist:
- Capture the status code, route, method, correlation ID, environment, and timestamp.
- Identify the first component that rejected the request.
- Confirm credential transport without copying the secret into logs or tickets.
- Check issuer, audience, expiration, not-before time, algorithm, key ID, and available verification keys.
- Check scopes, roles, tenant context, resource ownership, and route policy.
- Compare direct and gateway requests, plus browser and non-browser behavior where relevant.
- Test a safe remediation, record the configuration change, and verify both allowed and denied cases.
After resolution, record the failure mode, detection signal, affected boundary, and prevention step. Update the relevant runbook and, if the issue involved infrastructure or deployment drift, review the infrastructure drift detection workflow. A small, maintained record of these checkpoints turns the next API authentication error from a guess-and-check exercise into a controlled diagnostic process.