HTTP 401 Unauthorized means the request lacks valid authentication credentials, while HTTP 403 Forbidden means the server understood the request and refuses to fulfill it.[1][2] In short: 401 asks "who are you?" and 403 answers "permission denied." Despite the historical label "Unauthorized," RFC 9110 defines 401 around authentication, and requires every 401 response to carry a WWW-Authenticate header explaining how to authenticate.[1][3] This guide covers the exact RFC 9110, RFC 6750, and RFC 9111 rules, when to return 404 instead of 403, production server and client code patterns, and the mistakes that break API auth flows. To look up any response code alongside its headers and retry behavior, open the HTTP status codes reference.
401 vs 403 at a glance
The fastest way to separate the two codes is to check whether the server could verify the caller's identity and whether retrying with refreshed credentials can fix the error.[1][2]
| Dimension | 401 Unauthorized | 403 Forbidden |
|---|
| Core meaning (RFC 9110) | Request lacks valid authentication credentials for the target resource[1] | Server understood the request but refuses to fulfill it[2] |
| Security concept | Authentication (identity missing, expired, or invalid)[1][6] | Authorization or policy refusal (role, scope, IP, or state)[2][7] |
| WWW-Authenticate header | MUST be sent with at least one challenge[1][3] | Optional; server MAY send it (e.g., OAuth 2.0 insufficient_scope)[3][4] |
| OAuth 2.0 Bearer error (RFC 6750) | invalid_token (expired, revoked, or malformed token)[4] | insufficient_scope (valid token lacking required scope)[4] |
| Client retry behavior | Client MAY retry with a new or replaced Authorization header[1] | Client SHOULD NOT automatically repeat with the same credentials[2] |
| Heuristic caching (RFC 9110) | Not heuristically cacheable[5] | Not heuristically cacheable[5] |
| Can hide resource existence? | No — signals the endpoint requires authentication | Server MAY return 404 Not Found instead to hide existence[2] |
Why 401 is called "Unauthorized" even though it means unauthenticated
The name 401 Unauthorized causes more API design bugs than almost any other HTTP status code. In everyday security vocabulary, authentication verifies who is making a request, while authorization checks what that verified identity is allowed to do. HTTP kept the original 1990s reason phrase "Unauthorized" for backwards compatibility, even though RFC 9110 Section 15.5.2 defines 401 explicitly in terms of authentication: "the request has not been applied because it lacks valid authentication credentials for the target resource."[1]
RFC 9110 Section 15.1 also notes that reason phrases are only recommendations and can be omitted or replaced without affecting the protocol (HTTP/2 and HTTP/3 do not even transmit reason phrases on the wire).[5] Treat the numeric code 401 as "unauthenticated" and 403 as "forbidden," as both MDN Web Docs and the OWASP REST Security Cheat Sheet do.[6][7][8]
What RFC 9110 requires for 401 Unauthorized
Return 401 when the caller has not proven a valid identity for the request:
No
Authorizationheader, session cookie, or API key was supplied on a protected route.A JWT or OAuth access token has expired, failed signature verification, has the wrong audience or issuer, or was revoked.[4]
A session cookie has expired or was invalidated server-side on logout.
HTTP Basic credentials have an unknown username or wrong password.
There is one hard normative rule that many REST APIs overlook. Under RFC 9110 Section 15.5.2 and Section 11.6.1, a server generating a 401 response MUST send a WWW-Authenticate header field containing at least one challenge applicable to the target resource.[1][3] Proxies forwarding that response MUST NOT modify any WWW-Authenticate header fields.[3]
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api"
Content-Type: application/json
{"error":"authentication_required","message":"Provide a valid Bearer token."}
If the client already sent an expired or invalid Bearer token, RFC 6750 Section 3.1 specifies that the resource server SHOULD respond with 401 and include error="invalid_token" in the challenge. When the request carried no credentials at all, RFC 6750 says the server SHOULD NOT include an error code or error details in WWW-Authenticate — send a bare Bearer realm="..." challenge instead.[4]
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token", error_description="The access token expired"
Content-Type: application/json
{"error":"invalid_token","message":"Access token expired. Refresh and retry."}
Notice what RFC 9110 Section 15.5.2 says about retry loops: the user agent MAY repeat the request with a new or replaced Authorization header, and if the server returns the same challenge after authentication was already attempted, the user agent SHOULD show the diagnostic response rather than looping indefinitely.[1]
What RFC 9110 requires for 403 Forbidden
Return 403 when the server understood the request and is refusing to carry it out.[2] Two distinct categories fall under 403:
Authenticated caller, insufficient privileges: The token or session is valid, so the server knows who the caller is, but the caller lacks the role, tenant membership, plan entitlement, or OAuth scope needed for the action.[2][4][8]
Policy refusal unrelated to credentials: RFC 9110 Section 15.5.4 explicitly notes that "a request might be forbidden for reasons unrelated to the credentials."[2] Common examples include IP allowlist blocks, geo-restrictions, WAF rules, disabled accounts, or write attempts on a read-only resource.
Because re-sending the exact same credentials will not change the server's policy decision, RFC 9110 Section 15.5.4 states that the client SHOULD NOT automatically repeat the request with the same credentials (though it MAY retry with new or different credentials, such as a token that carries a higher scope).[2]
For OAuth 2.0 Bearer tokens, RFC 6750 Section 3.1 defines the exact 403 pattern when a valid token lacks required scopes: return 403 Forbidden with error="insufficient_scope" and optionally list the missing scopes in the scope attribute.[4]
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer realm="api", error="insufficient_scope", scope="billing:write"
Content-Type: application/json
{"error":"insufficient_scope","required_scope":"billing:write"}
When debugging whether an API returned 401 or 403 for a JWT, inspect the token's exp timestamp versus its scope or role claims in the JWT decoder. An expired exp belongs in 401; a valid, unexpired token missing the required claim belongs in 403.
OAuth 2.0 Bearer error mapping: 400 vs 401 vs 403
API teams often lump malformed auth headers together with expired tokens. RFC 6750 Section 3.1 separates three failure modes across three distinct status codes:[4]
| RFC 6750 error code | HTTP status | When to use it |
|---|
| invalid_request | 400 Bad Request | Missing required parameter, duplicate parameter, malformed syntax, or sending an access token in more than one place (for example, both a header and query string)[4] |
| invalid_token | 401 Unauthorized | Token is expired, revoked, malformed, or otherwise fails verification; client may fetch a fresh token and retry[4] |
| insufficient_scope | 403 Forbidden | Token is valid, but the endpoint requires higher privileges; server may advertise needed scopes via scope="..."[4] |
When to return 404 instead of 403 (and the caching trap)
Returning 403 Forbidden on an ID-addressed endpoint such as GET /api/invoices/inv_98421 confirms to the caller that invoice inv_98421 exists, even though the caller is not allowed to read it. If an attacker iterates through IDs, 403 versus 404 leaks which records exist in the database.
RFC 9110 Section 15.5.4 explicitly authorizes hiding private resources behind 404: "An origin server that wishes to 'hide' the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found)."[2] Section 15.5.5 mirrors that rule in the definition of 404: the server either did not find a representation "or is not willing to disclose that one exists."[5]
Use this split in practice:
Return 404 instead of 403 for private, user-scoped, or tenant-scoped records where confirming existence is a data leak (invoices, private repositories, direct messages, another organization's documents).
Return 403 for known capability or role checks where the endpoint's existence is public (for example, a logged-in member calling
POST /api/org/billing/planwithout the admin role, or a valid OAuth token missingreports:write).
Watch the caching difference when swapping 403 for 404. Under RFC 9110 Section 15.1, neither 401 nor 403 is heuristically cacheable, whereas 404 is heuristically cacheable by default unless explicit cache controls prevent it.[5] Under RFC 9111 Section 3.5, a shared cache must not reuse a cached response to a request containing an Authorization header unless the response includes must-revalidate, public, or s-maxage.[9] Cookie-authenticated endpoints do not carry an Authorization header, so always send Cache-Control: private, no-store on authenticated endpoints that mask 403 as 404 — otherwise a misconfigured CDN could cache one user's 404 and serve it to the record's actual owner.
401 vs 403 vs 407: where proxies fit
Corporate networks and egress proxies introduce a third authentication code: 407 Proxy Authentication Required. RFC 9110 Section 15.5.8 defines 407 as parallel to 401, except the challenge comes from an HTTP proxy rather than the origin server.[5] The proxy MUST send a Proxy-Authenticate header, and the client answers with Proxy-Authorization. Application servers should never return 407 for app-level login failures; reserve 401 for origin authentication and 403 for origin authorization.
Production server pattern: separating authN and authZ
Clean server code evaluates authentication first and authorization second so a missing token never falls through to a 403 and a missing role never triggers a token-refresh loop. Here is a minimal Next.js Route Handler pattern (for full route middleware architecture, see the Next.js 16 API routes and middleware guide):
import { NextRequest, NextResponse } from 'next/server'
interface VerifiedUser {
id: string
orgId: string
scopes: string[]
}
async function verifyBearerToken(header: string | null): Promise {
if (!header?.startsWith('Bearer ')) {
return { ok: false, reason: 'missing' }
}
const token = header.slice('Bearer '.length).trim()
if (!token) return { ok: false, reason: 'missing' }
// Replace with signature, exp, iss, and aud verification
const user = await lookupAndVerifyJwt(token)
return user ? { ok: true, user } : { ok: false, reason: 'invalid' }
}
export async function DELETE(
req: NextRequest,
context: { params: Promise },
) {
const auth = await verifyBearerToken(req.headers.get('authorization'))
// 1. Authentication check -> 401 + mandatory WWW-Authenticate
if (!auth.ok) {
const challenge =
auth.reason === 'missing'
? 'Bearer realm="api"'
: 'Bearer realm="api", error="invalid_token"'
return NextResponse.json(
{ error: auth.reason === 'missing' ? 'authentication_required' : 'invalid_token' },
{
status: 401,
headers: { 'WWW-Authenticate': challenge, 'Cache-Control': 'no-store' },
},
)
}
// 2. Scope / role check -> 403 with required scope
if (!auth.user.scopes.includes('projects:delete')) {
return NextResponse.json(
{ error: 'insufficient_scope', required_scope: 'projects:delete' },
{
status: 403,
headers: {
'WWW-Authenticate':
'Bearer realm="api", error="insufficient_scope", scope="projects:delete"',
'Cache-Control': 'no-store',
},
},
)
}
// 3. Tenant ownership check -> 404 to avoid leaking foreign IDs
const { id } = await context.params
const project = await findProjectForOrg(id, auth.user.orgId)
if (!project) {
return NextResponse.json(
{ error: 'not_found' },
{ status: 404, headers: { 'Cache-Control': 'private, no-store' } },
)
}
await deleteProject(project.id)
return new NextResponse(null, { status: 204 })
}
Every branch maps directly to the RFC rules above: missing tokens get a bare 401 challenge, bad or expired tokens get 401 with error="invalid_token", missing scopes get 403 with error="insufficient_scope", and cross-tenant ID lookups return a non-cached 404.
Client-side handling: refresh on 401 once, never auto-retry 403
The biggest operational reason to keep 401 and 403 distinct is client interceptor behavior. Most HTTP clients and frontend SDKs attach an interceptor that watches for 401, exchanges a refresh token for a new access token, and replays the failed request once. If your backend accidentally sends 401 when a user lacks an admin role, that interceptor refreshes a valid token, replays the request, gets another 401, and either loops or logs the user out.
Follow three client rules:
On 401: Attempt a single credential refresh (if the request has not already been retried), replay once with the new
Authorizationheader, and redirect to sign-in or surface an auth error if the second attempt still returns 401.[1]On 403: Do not automatically retry with the same credentials, and do not wipe the user's session.[2] Show a clear permission message or prompt for step-up consent if the response advertises a required OAuth
scope.Backoff applies to transient errors, not 403: Exponential backoff is for transient faults such as
429or503— model those retry schedules with the exponential backoff calculator, and exclude403from automatic retries.
Five common 401 and 403 mistakes to avoid
Returning 401 without
WWW-Authenticate: Violates RFC 9110 Section 15.5.2's MUST requirement and breaks strict HTTP/OAuth clients that inspect the challenge to decide how to re-authenticate.[1]Returning 401 for missing roles or permissions: Causes SPA and mobile interceptors to treat a valid session as logged out and trigger unnecessary token refreshes or forced sign-outs.
Returning 403 for expired tokens: Prevents the client from triggering silent token refresh, leaving users stuck on a "permission denied" screen until they manually reload and sign in again.
Returning 403 on cross-tenant object IDs: Lets callers enumerate valid IDs belonging to other customers instead of returning
404withCache-Control: private, no-store.[2]Returning 200 OK with an error JSON body: Breaks standard HTTP tooling, telemetry, alerting, and caches — OWASP explicitly advises returning the semantically appropriate status code rather than wrapping auth errors in 200 or 404.[8]
Quick decision checklist
No credentials provided on a protected endpoint? Return 401 with
WWW-Authenticate: Bearer realm="..."(noerrorparameter).[1][4]Credentials expired, revoked, or invalid signature? Return 401 with
WWW-Authenticate: Bearer realm="...", error="invalid_token".[4]Malformed auth header or duplicate token transport? Return 400 with
invalid_request.[4]Valid credentials, but wrong role, plan, or OAuth scope? Return 403 (optionally with
error="insufficient_scope"andscope="...").[2][4]Blocked by IP allowlist, WAF, or account suspension? Return 403.[2]
Authenticated user requesting another tenant's private ID? Return 404 with
Cache-Control: private, no-store.[2][5]Proxy requires credentials before forwarding? Return 407 with
Proxy-Authenticate.[5]
Sources
401 Unauthorized — HTTP Status Codes, MDN Web Docs (accessed November 24, 2026)
403 Forbidden — HTTP Status Codes, MDN Web Docs (accessed November 24, 2026)
REST Security Cheat Sheet — HTTP Return Codes, OWASP Cheat Sheet Series (accessed November 24, 2026)
9. RFC 9111: HTTP Caching, Section 3.5 — Storing Responses to Authenticated Requests, IETF, June 2022 (accessed November 24, 2026)
Originally published at wowhow.cloud
Top comments (0)