Per RFC 9110 §15.5.2, HTTP 401 Unauthorized strictly means Unauthenticated: the target resource requires valid identity credentials, and the request either arrived with no credentials (stripped by a 301 redirect, proxy, or missing credentials fetch option) or presented a token/cookie that failed cryptographic signature, iss/aud claim, exp/nbf clock-skew, or key-ID (kid) verification. Furthermore, RFC 9110 mandates that every 401 response must include a WWW-Authenticate header (such as WWW-Authenticate: Bearer error="invalid_token", error_description="The access token expired")—making curl -i your fastest diagnostic lens before reading a single line of backend code.
While missing Bearer prefixes are easy to spot in development, production 401 outages almost always stem from subtler distributed-systems failure modes: OIDC JWKS key-rotation cache races, HTTP 301/302 cross-origin Authorization stripping, VM NTP clock drift on nbf, and reverse-proxy SameSite/Secure cookie mismatches.
| Production Symptom | Underlying Protocol / Crypto Cause | Diagnostic Check | Permanent Fix |
|---|---|---|---|
Works in curl, returns 401 on http:// or www. URL |
Fetch/cURL strips Authorization header across scheme (http->https) or host 301/302 redirects! |
curl -iL shows 301 followed by 401 on hop 2 |
Call canonical https:// API base URL directly; return 308 only on same-origin |
| 100% of logins fail suddenly every few days/weeks for ~1 hr | OIDC JWKS kid rotation race: IdP rotated signing key while API cached stale jwks.json |
JWT header kid missing from API's cached keyset |
Refetch /.well-known/jwks.json on unknown kid with a 30s rate-limit cooldown |
Freshly minted JWT immediately fails 401 (jwt not active) |
nbf (Not Before) clock skew: Issuing auth server is 4s ahead of API VM's system clock |
chronyc tracking shows multi-second offset |
Sync all nodes via chrony NTP and configure clockTolerance: '5s' in JWT verifier |
| Valid JWT rejected after switching IdP / environment | Trailing-slash iss or aud mismatch: "https://idp.io" != "https://idp.io/" |
Inspect payload via jq -R 'split(".")|.[1]|@base64d|fromjson' |
Match exact RFC 8414 issuer byte-for-byte and pin expected aud API identifier |
Browser login returns 200, next API call returns 401 |
Cookie carries Secure flag, or SameSite=Lax blocked cross-site XHR, or Nginx dropped X-Forwarded-Proto |
DevTools Network -> Set-Cookie warning icon |
Set X-Forwarded-Proto https at proxy; use credentials: 'same-origin' (or 'include' + explicit CORS origin) |
Apache / FastCGI backend receives empty Authorization |
Apache CGI/FastCGI strips HTTP_AUTHORIZATION by default for legacy security |
Print incoming request headers in app handler | Add CGIPassAuth On (Apache) or ensure Nginx isn't overriding proxy_set_header Authorization |
Never paste production JWTs into random web-based JWT debugger sites—an active Bearer token grants full impersonation until exp expires! Instead, inspect both the server's RFC 6750 WWW-Authenticate header and your local token's header/payload offline in one terminal pipeline:
# 1. Inspect exact HTTP status, redirects, and RFC 6750 WWW-Authenticate error code
curl -i -sS https://serversareup.com/api/v1/instances \
-H "Authorization: Bearer $SAU_API_TOKEN" | head -n 20
# 2. Safely decode a JWT's Header (alg, kid) and Payload (iss, aud, exp, nbf) locally in Bash
decode_jwt() {
printf '%s' "$1" | awk -F. '{
for (i = 1; i <= 2; i++) {
s = $i; gsub(/-/, "+", s); gsub(/_/, "/", s);
while (length(s) % 4) s = s "=";
print s
}
}' | while read -r part; do printf '%s' "$part" | base64 -d 2>/dev/null | jq .; done
}
# Compare token exp / nbf directly against this server's current UTC epoch:
echo "Local UTC Epoch: $(date -u +%s)"
# decode_jwt "$ACCESS_TOKEN"
If you are authenticating against the ServersAreUp REST API or MCP Server using a Personal Access Token (sau_...), check /account/api-keys to confirm the token hasn't expired or been revoked—and remember: if your token authenticates (200 on /api/v1/instances) yet fails on a destructive action like power-off, the API returns 403 Forbidden (missing scope instances:power), not 401.
alg ConfusionIn modern OAuth 2.0 / OIDC architectures (Auth0, Keycloak, Microsoft Entra ID, Google Identity, Ory), the authorization server signs asymmetric JWTs (EdDSA, ES256, or RS256) with a private key identified by a kid (Key ID) header and publishes the matching public keys at https://<issuer>/.well-known/jwks.json.
Two deadly implementation bugs show up when engineers hand-roll JWKS verification:
jwks.json only at container boot (or caches it blindly for 24 hours), the instant your identity provider performs routine cryptographic key rotation and starts signing tokens with kid: "2026-q4-key", every newly logged-in user receives 401 Unauthorized until you restart your fleet! Conversely, if you naively refetch jwks.json on every unknown kid without rate-limiting, an attacker can flood your API with garbage kid: "random-uuid" headers, turning your backend fleet into an outbound request-flood amplifier against your own identity provider!iss/aud: Verifying only the cryptographic signature without pinning allowed algorithms (['EdDSA', 'ES256', 'RS256']), exact issuer, and exact audience allows cross-service token replay: a valid JWT minted by the same IdP for your public docs feedback widget (aud: "docs-widget") will happily authenticate against your billing admin API (aud: "billing-api") if audience isn't enforced!Here is the battle-tested TypeScript implementation using jose that handles zero-downtime kid key rotation with built-in cooldown protection, explicit algorithm pinning, and 5-second NTP clock-skew tolerance:
// TypeScript / Node.js / Edge: Hardened OIDC JWT verification with safe JWKS rotation
import { createRemoteJWKSet, jwtVerify, errors as JoseErrors } from 'jose';
const ISSUER = 'https://auth.yourdomain.com';
const AUDIENCE = 'https://api.yourdomain.com';
// Caches JWKS in memory; on unknown 'kid', refetches AT MOST once every 30,000 ms (cooldownDuration)!
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`), {
cooldownDuration: 30_000,
cacheMaxAge: 600_000,
timeoutDuration: 3_000,
});
export async function authenticateBearer(authHeader: string | null) {
if (!authHeader?.startsWith('Bearer ')) {
return { ok: false as const, error: 'invalid_request', desc: 'Missing Bearer token' };
}
const token = authHeader.slice(7).trim();
try {
const { payload } = await jwtVerify(token, jwks, {
issuer: ISSUER,
audience: AUDIENCE,
algorithms: ['EdDSA', 'ES256', 'RS256'], // Never allow symmetric HS256 against public JWKS!
clockTolerance: '5s', // Absorbs minor sub-5s VM NTP drift on nbf / exp
});
return { ok: true as const, sub: payload.sub, scopes: String(payload.scope ?? '').split(' ') };
} catch (err) {
const desc = err instanceof JoseErrors.JWTExpired ? 'Token expired' : 'Token verification failed';
return { ok: false as const, error: 'invalid_token', desc };
}
}
Two HTTP transport rules routinely fool experienced frontend and mobile developers:
curl): Suppose your mobile app sends Authorization: Bearer ... to http://api.example.com/v1/me or https://example.com/api/v1/me, and Nginx issues a 301 Moved Permanently to https://www.example.com/api/v1/me. Because forwarding secret Authorization headers to a redirected host or downgraded scheme would leak tokens on open redirects, fetch(), axios, Python requests, Go net/http, and curl -L intentionally delete the Authorization header when following cross-host redirects! The second request arrives anonymous and fails with 401. Always configure clients with the final canonical https:// URL directly.OPTIONS Preflight Unauthenticated Rejection: Browser CORS preflight OPTIONS requests never include Authorization headers or cookies by W3C specification! If your auth middleware intercepts OPTIONS /api/v1/orders before your CORS middleware runs and returns 401, the browser aborts the preflight and blocks your fetch() call entirely. Always respond 204 No Content with CORS headers to OPTIONS preflights ahead of authentication checks.When HTTP/1.0 was drafted in the early 1990s, the original authors conflated authentication and authorization terminology—and once billions of clients depended on status code 401 triggering WWW-Authenticate credential prompts, the wire text could never be renamed without breaking backward compatibility. RFC 9110 explicitly clarifies that 401 means unauthenticated, while 403 Forbidden means unauthorized.
Access-Control-Allow-Origin: * when sending cookies or credentials: 'include'?The Fetch specification forbids browsers from exposing responses when credentials: 'include' is paired with a wildcard Access-Control-Allow-Origin: * (otherwise any malicious tab could make credentialed cross-site reads!). Your server must echo a strict allow-listed origin (e.g., Access-Control-Allow-Origin: https://app.yourdomain.com) plus Access-Control-Allow-Credentials: true and Vary: Origin.
If a React dashboard mounts 8 parallel fetch() components the second an access token expires, all 8 calls receive 401 simultaneously—and if each component calls POST /oauth/token independently with a rotating refresh token (Refresh Token Rotation), request #1 succeeds and invalidates the old refresh token, causing requests #2–#8 to trigger refresh-token reuse detection and forcibly log the user out! Deduplicate token refreshes in your client HTTP interceptor using a single shared in-flight Promise mutex.
POST /api/auth/login with wrong password) return 401 or 400?Return 401 Unauthorized for valid payload formats carrying incorrect credentials (wrong password, invalid TOTP code), and reserve 400 Bad Request / 422 for structurally invalid payloads (missing email field or malformed JSON). Be sure both wrong-username and wrong-password paths execute a dummy argon2id/bcrypt hash check in constant time so response latency doesn't allow attackers to enumerate registered email addresses!
Explore With AI & Cite This Page
Open a grounded prompt in your AI assistant or copy a clean Markdown, HTML, or APA reference link.
Validate protocols and subnets directly in your browser or continue reading related architecture notes.
SSL/TLS & Security Headers Checker (HSTS, CSP)
Free JWT Decoder, Base64URL & SHA-256 Tool
Online TCP Port Checker — Ports 443, 22, 25565
Understanding and Resolving HTTP 403 Forbidden: Linux VFS Traverse Bits, SELinux, Reverse Proxies & Object Storage
Debug HTTP 403 Forbidden errors across every stack layer: Linux parent-directory +x traverse bits (namei -l), SELinux httpd_sys_content_t labels, Nginx autoindex/try_files, S3/Blob SAS clock skew, and Cloudflare WAF.
Enterprise SAML 2.0 & OIDC Engineering Guide: XML Signature Wrapping (XSW), PKCE S256 & ES256 JWKS
Deep protocol and security guide to SAML 2.0 and OpenID Connect (OIDC) SSO with Entra ID, Okta, and Google Workspace: defending against XML Signature Wrapping (XSW) and XXE, implementing OIDC PKCE (S256) + ES256 JWKS rotation, and troubleshooting clock skew.
Mastering ssh-keygen in Linux: Ed25519 Internals, FIDO2 Hardware Keys, and OpenSSH Certificates
Generate hardened Ed25519 and FIDO2 hardware-backed SSH keys with ssh-keygen, tune bcrypt KDF rounds, eliminate authorized_keys sprawl with OpenSSH Certificates, and automate ephemeral key leasing.
Passkeys (WebAuthn) & Federated OAuth 2.0 PKCE Guide: rpId Origin Binding, Resident Keys & Attestation
Inside FIDO2/WebAuthn Passkeys and federated OAuth 2.0 PKCE authentication: how rpId origin binding defeats AitM phishing, residentKey discoverable credentials, attestation vs synced passkey flags (BE/BS), and TypeScript verification code.