401 vs 403: Unauthorized vs Forbidden, and When to Use Each
401 and 403 both mean “you cannot have this”, but for different reasons. 401 Unauthorized means the server does not know who you are; 403 Forbidden means it knows and still says no. Learn the rule, the WWW-Authenticate header, when to return 404 instead, how clients should react, and how to test it, with a local server we ran.
- 401 vs 403 is authentication vs authorization: 401 means “who are you?”, 403 means “I know you, and the answer is no”.
- Return 401 when credentials are missing, invalid or expired, and include a
WWW-Authenticateheader. - Return 403 when a valid user lacks permission. Logging in again will not help.
- To hide that a private resource exists, return 404 instead of 403, as our server did for another user’s order.
Few HTTP mistakes are as common in APIs as getting 401 vs 403 wrong. The names do not help: “Unauthorized” actually describes an authentication problem, while “Forbidden” is the authorization one. Getting them right matters, because browsers, mobile apps and API clients decide what to do next, show a login screen or an “access denied” message, based on that number.
We built a small token-protected API server in Python (3.13.6, standard library only) and called it as anonymous, expired, invalid, ordinary and admin users. Every response below is from that run. For the full list of codes, see our HTTP status codes cheat sheet.
401 vs 403: the short answer
| Aspect | 401 Unauthorized | 403 Forbidden |
|---|---|---|
| Meaning | Not authenticated | Authenticated, but not allowed |
| Question it answers | Who are you? | What are you allowed to do? |
| Typical cause | Missing, invalid or expired credentials | Wrong role, plan or ownership |
| Will retrying with credentials help? | Yes | No |
| Required header | WWW-Authenticate |
None |
Authentication vs authorization
Authentication proves identity: a password, a session cookie, an API key or a token such as a JWT. Authorization decides what that identity may do: roles, permissions, plan limits, ownership of a record. Every protected request goes through both checks, in that order. A failure in the first step is a 401; a failure in the second is a 403.
401 Unauthorized
The current HTTP specification (RFC 9110, which replaced RFC 7231 and RFC 7235) defines 401 as a request that lacks valid authentication credentials for the resource. Return it when:
- No credentials were sent.
- The token or password is wrong, malformed or revoked.
- The session or token has expired.
The key property of a 401 is that the client can fix it by authenticating, so a login prompt or a token refresh is the right reaction.
The WWW-Authenticate header
The specification requires a 401 response to include WWW-Authenticate, telling the client how to authenticate. Our server sent:
WWW-Authenticate: Bearer realm="shop" (no token)
WWW-Authenticate: Bearer error="invalid_token", error_description="expired" (expired)
WWW-Authenticate: Bearer error="invalid_token" (bogus token)
For bearer tokens, the OAuth 2.0 bearer token standard (RFC 6750) defines the error values, so a client can tell “refresh your token” apart from “you never sent one”. For Basic authentication, this header is what makes a browser show its built-in login dialog.
403 Forbidden
403 means the server understood the request and knows who is asking, but refuses to authorise it. Typical cases:
- A viewer tries an admin action.
- A free-plan user calls a paid feature.
- A request comes from a blocked IP range or country.
- A CSRF check fails on a logged-in session.
Re-sending the same credentials will never succeed, so clients should not prompt for login again. Instead they should explain the restriction, or offer a way to request access or upgrade.
What our test server returned
200 /public token=None {'ok': True}
401 /admin/refunds token=None {'error': 'missing token'}
401 /admin/refunds token=tok-old {'error': 'token expired'}
401 /admin/refunds token=bogus {'error': 'invalid token'}
403 /admin/refunds token=tok-viewer {'error': 'admin role required'}
200 /admin/refunds token=tok-admin {'user': 'ravi', 'path': '/admin/refunds'}
404 /orders/99 token=tok-viewer {'error': 'not found'}
200 /orders/99 token=tok-admin {'user': 'ravi', 'path': '/orders/99'}
The server applies the checks in order. No token, an expired token and an unknown token all produced 401, each with its own WWW-Authenticate detail. A valid viewer token passed authentication but failed the role check, so it got 403. The admin succeeded. The core of the handler:
if tok is None:
return self.send(401, {"error": "missing token"},
{"WWW-Authenticate": 'Bearer realm="shop"'})
user = TOKENS.get(tok)
if not user:
return self.send(401, {"error": "invalid token"},
{"WWW-Authenticate": 'Bearer error="invalid_token"'})
if self.path == "/admin/refunds" and user["role"] != "admin":
return self.send(403, {"error": "admin role required"})
Decision table: which code to return
| Situation | Status |
|---|---|
| No credentials on a protected endpoint | 401 |
| Wrong password or invalid token | 401 |
| Expired session or token | 401 |
| Valid user, missing role or permission | 403 |
| Valid user, feature not in their plan | 403 |
| Valid user, record belongs to someone else and must stay secret | 404 |
| Too many requests | 429 (see rate limiting) |
| Browser blocked a cross-origin response | Not a status code; see CORS |
When 404 is better than 403
A 403 confirms that a resource exists. For many resources that is a leak: if /orders/99 returns 403 for strangers and 404 for nonexistent IDs, an attacker can enumerate which order numbers are real. Our server returned 404 when the viewer asked for someone else’s order and 200 to its owner. The HTTP specification explicitly allows a server to answer 404 instead of 403 when it does not want to reveal that the resource exists. Use 403 when the existence is not secret, such as an admin page everyone knows about; use 404 for private records.
Tip: make the “not yours” and “does not exist” responses identical in status, body and timing, so they cannot be told apart.
How clients should react
- 401: try a silent token refresh once; if that fails, clear the session and send the user to log in. Do not loop forever.
- 403: do not log the user out. Show a clear “you do not have access” message, hide the forbidden action, or offer an upgrade or access request.
- 404 on a private resource: show “not found”; do not hint that it might exist.
Session cookies are covered in our HTTP cookies guide.
401 and 403 on websites and SEO
Search engines treat both codes as “cannot access”, and will not index the content behind them, which is what you want for account pages. Problems appear when public pages return them by mistake: a firewall or bot protection that sends 403 to crawlers, or a staging password left on a live site. Monitor crawl errors for unexpected 401 and 403 responses, and never protect public pages with them.
Testing auth errors
- For each protected endpoint, test: no token, malformed token, expired token, valid token without permission, valid token with permission.
- Assert the status and the
WWW-Authenticateheader for 401 responses. - Check that one user cannot read another user’s records by changing an ID in the URL, the classic broken object level authorization bug.
- Make sure error bodies do not leak details such as “user exists but password wrong”.
Our API testing with Python guide shows how to automate these checks.
Common mistakes
- Returning 403 for a missing or expired token, which stops clients from refreshing and logging in.
- Returning 401 to a logged-in user who lacks permission, causing endless login loops.
- Omitting
WWW-Authenticateon 401 responses. - Using 403 for private records and revealing that they exist.
- Returning 200 with an error message in the body.
Logging and monitoring 401 and 403
Authentication errors are a useful security signal. A sudden rise in 401 responses from one IP address can mean password guessing or a leaked list of tokens being tried, while a burst of 403 responses from one valid account can mean someone probing for data they should not see. Log every 401 and 403 with the route, the authenticated user if known, the client IP and a reason code, but never the token or password itself. Track the rates on a dashboard, alert on spikes, and combine them with rate limiting to slow down attacks. After a release, a jump in 401s often points to a broken token refresh in the client rather than an attack, so the same metric doubles as a deployment health check.
Final thoughts
The 401 vs 403 rule fits in one line: 401 when the server cannot tell who you are, 403 when it knows and refuses. Send WWW-Authenticate with every 401, never log users out on a 403, and prefer 404 when even admitting that a resource exists would leak information. With those three habits, your API speaks clearly to every client that calls it. For designing the rest of your API, see REST API best practices.
Frequently asked questions
What is the difference between 401 and 403?
401 Unauthorized means the request has no valid credentials, so the server does not know who you are. 403 Forbidden means the server knows who you are but you do not have permission.
Should an expired token return 401 or 403?
401. An expired token is an authentication problem the client can fix by refreshing or logging in again, and the response should include a WWW-Authenticate header.
Why is 401 called Unauthorized if it means unauthenticated?
It is a historical naming quirk in the HTTP specification. The meaning has always been missing or invalid authentication, which is why the 401 response carries a WWW-Authenticate header.
When should I return 404 instead of 403?
When revealing that a resource exists would leak information, such as a private order that belongs to someone else. Returning 404 makes it look the same as a resource that does not exist.
Will logging in again fix a 403 error?
Usually not. A 403 means your identity is known but lacks permission. You need a different role, plan or access grant, not new credentials.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.