Prompt
How do I fix repeated 401s and 403s on protected API endpoints?
Latest observation
Repeated 401 Unauthorized and 403 Forbidden responses usually mean one of a few things:
- 401: the request is missing valid authentication
- 403: the request is authenticated, but the user/app lacks permission
Here’s a practical checklist to fix them.
1) Confirm which code is happening
- 401 = credentials are absent, expired, malformed, or not accepted
- 403 = credentials are valid, but access is denied by authorization rules
That distinction matters because the fix is different.
2) Verify the Authorization header
For bearer-token APIs, ensure requests include:
Authorization: Bearer <access_token>
Common mistakes:
- missing
Bearer - extra quotes
- sending the refresh token instead of access token
- token copied with whitespace/newlines
- header stripped by a proxy or gateway
3) Check token expiration and refresh logic
Repeated 401s often happen because the access token expired.
Make sure your client:
- checks token expiry before calling protected endpoints
- refreshes the token when needed
- retries the request after a successful refresh
- does not keep using an old token from cache/local storage
If refresh fails, force re-login.
4) Validate audience, issuer, and scope claims
A token can be “valid” but still rejected if claims don’t match what the API expects.
Check:
- issuer (
iss) - audience (
aud) - scope / roles / permissions
- tenant / organization ID
- environment mismatch: prod token used against staging API, or vice versa
If the API expects a token for a specific audience, an access token for another service will return 401/403.
5) Inspect authorization rules for 403s
403s are often caused by:
- missing role/group membership
- insufficient OAuth scopes
- policy-based authorization denying access
- resource ownership checks failing
- IP allowlists, mTLS, or device/user restrictions
Review:
- endpoint-level permissions
- middleware/policies
- RBAC/ABAC rules
- feature flags or admin-only routes
6) Check CORS / preflight behavior
Sometimes the browser hides the real issue.
If the frontend runs in a browser:
- the OPTIONS preflight request may be failing
- auth headers may not be allowed by CORS config
- cookies may not be sent due to
SameSite,Secure, orwithCredentials
Make sure your API allows:
Authorizationheader- the correct origin
- credentials if using cookies
7) If using cookies/session auth, verify cookie settings
For cookie-based auth:
- cookie must be present on the request
- domain/path must match
Securerequires HTTPSSameSitecan block cross-site requests- session may expire server-side
In browsers, cross-origin API calls often need:
fetch(..., { credentials: 'include' })- backend CORS
Access-Control-Allow-Credentials: true
8) Check reverse proxy / gateway / load balancer behavior
A proxy can cause repeated auth failures if it:
- removes the
Authorizationheader - rewrites paths incorrectly
- terminates TLS and changes scheme/host assumptions
- caches auth responses incorrectly
- sends the request to a different backend instance with no shared session store
If you use nginx, API gateways, or service meshes, inspect their auth/header forwarding config.
9) Look for clock skew
JWTs and signed tokens depend on time.
If server/client clocks differ:
- token may appear not-yet-valid (
nbf) - token may appear expired (
exp)
Sync system clocks with NTP.
10) Avoid infinite retry loops
A common bug is blindly retrying 401/403:
- on 401, refresh once, then retry once
- if still failing, stop and surface the error
- don’t keep retrying invalid credentials
Otherwise you can create repeated 401/403 storms.
11) Log the right details
Add logs for:
- request path and method
- auth scheme used
- token presence/expiry
- user ID / subject
- scopes/roles
- exact reason from auth middleware
- correlation/request ID
Be careful not to log secrets or full tokens.
12) Test with a known-good request
Use curl or Postman with a freshly issued token:
curl -i \
-H "Authorization: Bearer $TOKEN" \
https://api.example.com/protected/resource
If this works but your app fails, the issue is likely in client code, storage, or header propagation.
Quick diagnosis guide
If you get 401:
Likely causes:
- missing token
- expired token
- invalid signature
- wrong issuer/audience
- header not reaching API
If you get 403:
Likely causes:
- token valid, but no permission
- missing scope/role
- policy denies access
- user not in required group
- resource ownership check fails
If you want, I can help you debug this with:
- your auth type (JWT, session cookie, OAuth2, API key)
- a sample request/response
- your backend stack (Express, Django, Spring, .NET, etc.)