401 Unauthorized and 403 Forbidden both refuse a request, but they tell the client different things. 401 means "I don't know who you are": the request has no credentials, or they're invalid, and authenticating could fix it. 403 means "I know who you are, and the answer is no": authenticating again won't help.
Getting this right matters most in APIs, because clients act on the status code. A 401 should make a client refresh its token or send the user to log in. A 403 should show a "no access" message and stop.
The short answer
| 401 Unauthorized | 403 Forbidden | |
|---|---|---|
| Question it answers | Who are you? | Are you allowed? |
| Can logging in fix it? | Yes | No |
| Required header | WWW-Authenticate |
None |
| Typical cause | Missing, expired or invalid token or cookie | Missing role, scope or ownership; blocked IP |
| What the client should do | Refresh the token once, or ask the user to log in | Show that access is denied; don't retry |
Choosing the status in an API
Run the checks in this order and return at the first one that fails:
- No credentials at all, such as no
Authorizationheader and no session cookie: return 401. - Credentials that don't check out: an expired, revoked or malformed token, a bad signature, or a token for another audience. Return 401. These are all the same to the client: get new credentials.
- A valid user who lacks permission, such as a missing role or OAuth scope, or a record they don't own: return 403, or 404 if the resource's existence is itself private (see below).
- A request refused whoever sends it, such as a blocked IP address, a firewall rule or a failed CSRF check: return 403.
Checks 1 and 2 are authentication, so they always come first. Don't check permissions for a user you haven't identified.
The WWW-Authenticate header
RFC 9110 requires every 401 response to include a WWW-Authenticate header naming at least one way to authenticate. For a token API, that's the Bearer scheme:
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"}
RFC 6750 defines three error codes for bearer tokens, and each maps to a status:
error value |
Status | Meaning |
|---|---|---|
invalid_request |
400 | The request is malformed, such as a token sent two different ways |
invalid_token |
401 | Expired, revoked, malformed or otherwise invalid token |
insufficient_scope |
403 | The token is valid but lacks a scope this endpoint needs |
The insufficient_scope case is the one place a 403 also carries WWW-Authenticate, so the client can see which scope to request:
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer realm="api", error="insufficient_scope", scope="projects:write"
Leave the header off a 401 and clients that negotiate the scheme, such as curl with --anyauth, have nothing to go on, and you lose the one place that explains why the token was rejected.
Implementing it
In Express, keep authentication and permission checks in separate middleware, so each one returns its own status:
function requireUser(req, res, next) {
const user = authenticate(req); // null when the token is missing or invalid
if (!user) {
res.set("WWW-Authenticate", 'Bearer realm="api"');
return res.status(401).json({ error: "not_authenticated" });
}
req.user = user;
next();
}
function requireRole(role) {
return (req, res, next) => {
if (!req.user.roles.includes(role)) {
return res.status(403).json({ error: "forbidden" });
}
next();
};
}
app.delete("/api/projects/:id", requireUser, requireRole("admin"), deleteProject);
The same split in FastAPI, with auto_error=False so your code, not the security class, decides the status when the header is missing:
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
bearer = HTTPBearer(auto_error=False)
def current_user(credentials: HTTPAuthorizationCredentials | None = Depends(bearer)):
user = verify_token(credentials.credentials) if credentials else None
if user is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, headers={"WWW-Authenticate": "Bearer"})
return user
def admin_user(user=Depends(current_user)):
if "admin" not in user.roles:
raise HTTPException(status.HTTP_403_FORBIDDEN)
return user
verify_token is where you check the signature, expiry, issuer and audience. Decoding a token isn't enough, as JWT decode vs verify explains.
403 or 404 for private resources
A 403 confirms that the resource exists. That's fine for an admin page everyone knows about, but not for /api/invoices/8812 when the invoice belongs to another customer: the difference between 403 and 404 tells an attacker which IDs are real.
When existence is private, return 404 to users who aren't allowed to see the resource, exactly as if it didn't exist. GitHub's API does this for private repositories, answering 404 rather than 403 so it doesn't confirm they exist. Use 403 when the user knows the resource exists and needs to be told they can't use it, such as a read-only member trying to delete a project.
Handling both in the client
Treat the two codes differently, and never loop:
async function api(url, options = {}) {
let response = await fetch(url, withToken(options));
if (response.status === 401) {
const refreshed = await refreshAccessToken(); // false when the refresh token is also invalid
if (!refreshed) return redirectToLogin();
response = await fetch(url, withToken(options)); // retry once
}
if (response.status === 403) {
throw new AccessDeniedError(url); // show "You don't have access", keep the user signed in
}
return response;
}
If the retried request still returns 401, send the user to log in instead of refreshing again. On a 403, keep the session: the user is signed in and may have access to everything else.
Common mistakes
- Returning 403 for a missing or expired token. The client can't tell "log in again" from "not allowed", so it either shows the wrong message or never refreshes the token.
- Sending a 401 without
WWW-Authenticate. It breaks the HTTP contract and hides the reason the token was rejected. - Using
WWW-Authenticate: Basicon an API called from a web app. Every 401 opens the browser's native login dialog. UseBearer. - Redirecting unauthenticated API calls to an HTML login page. The client gets a 200 with HTML instead of a 401, and
response.json()fails with Unexpected token '<' in JSON. Redirect browser page loads; answer API calls with 401. - Signing the user out on a 403. It throws away a valid session because of one forbidden action.
- Requiring authentication on CORS preflight requests. Browsers never send credentials with
OPTIONSpreflights, so the API returns 401 before the real request is made. The 401 guide covers this and other causes.
When the 403 doesn't come from your code
A 403 can come from anything between the client and your app: nginx refusing a directory without an index file, file permissions, a CDN or firewall rule, bot protection, or an S3 bucket policy. Check the response headers before you debug your own authorization: server, cf-ray or x-amz-request-id tell you which layer answered. The 403 Forbidden guide lists these causes and their fixes.
To reproduce a failing request with the exact headers the browser sent, use Copy as cURL, and inspect a token's exp, aud and iss claims with the JWT Decoder.