HTTP, TLS & Web Performance

403 Forbidden vs. 401 Unauthorized

Tell the two access errors apart, fix each one as a visitor or developer and choose the right code in your own application.

Key takeaways

  • 401 asks for authentication and must include a WWW-Authenticate header describing how to provide it.
  • 403 refuses the request, and repeating it with the same credentials is not expected to help.
  • A 403 can come from permissions, firewall or bot rules, file settings or network location, not only user roles.
  • Applications may answer 404 in place of 403 to avoid revealing that something exists.
  • Permission checks belong on the server, for every request and every object.

401 Unauthorized means the server needs valid proof of who you are and did not get it. Sign in, or send correct credentials, and the request may succeed. 403 Forbidden means the server understood the request and refuses it. Signing in again with the same account will not usually change that.

The names mislead. Despite the word "Unauthorized", 401 is about authentication, establishing identity. 403 is about refusal, most often authorization, deciding what an identity may do.

The two codes side by side

Authentication failure or refusal
401 Unauthorized Identity missing or not accepted Includes WWW-Authenticate Signing in or renewing a token can help Example: expired API token 403 Forbidden Request understood and refused No sign-in challenge required Same credentials will not help Example: member opening an admin page VS 401 Unauthorized Identity missing or not accepted Includes WWW-Authenticate Signing in or renewing a token can help Example: expired API token 403 Forbidden Request understood and refused No sign-in challenge required Same credentials will not help Example: member opening an admin page

Picture an office building. At the front desk, 401 is "please show your badge", including when your badge has expired. At a locked lab door, 403 is "we know who you are, and this badge does not open this room".

How 401 works

HTTP has a built-in challenge and response. The server rejects the request and names an accepted scheme:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="Staging site"

For Basic, the browser shows its own username and password box and resends the request with an Authorization header. The credentials are only Base64 encoded, which anyone can reverse, so Basic authentication is acceptable only over HTTPS.

APIs commonly use bearer tokens:

GET /orders HTTP/1.1
Authorization: Bearer EXAMPLE_TOKEN
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token"

Many ordinary websites do not use this machinery at all. When your session ends, they redirect you to a login page with a 302 or 303, which is friendlier for people but unhelpful for programs. APIs should return 401.

A relative, 407 Proxy Authentication Required, is the same challenge issued by a proxy, typically on a company network.

Why 403 happens

A 403 has many possible authors:

  • The account lacks the role or permission for that page or action.
  • The web server cannot read the file, or file permissions forbid it.
  • A folder has no index page and directory listing is switched off.
  • A web application firewall judged the request suspicious.
  • An access rule limits addresses, countries or networks.
  • A link to protected storage has expired or has an invalid signature.
  • A required anti-forgery token is missing or stale (some frameworks use their own code or message for this).
  • Hotlink protection rejects a file embedded from another site.

The standard permits the server to explain in the response body, so read the page. It may name the reason or give a reference ID.

Fixing them as a visitor

For a 401:

  1. Sign out completely and sign back in.
  2. Check the username, password and which account you are using.
  3. Clear that site's cookies if the login loops.
  4. Check that your device's date and time are correct, since time-limited tokens depend on them.

For a 403:

  1. Check the address; you may be requesting a folder or an internal page.
  2. Confirm you are signed into the account that should have access, which is easy to get wrong with both work and personal accounts.
  3. Turn off a VPN or switch networks to see whether an address rule is involved, if your organization's policies allow.
  4. Ask the site owner or your administrator for access, quoting any reference ID.

Do not try to get around a refusal. If you believe it is a mistake, report it to someone who can change the rule.

Debugging as a developer

Look at the whole exchange:

curl -i https://api.example.com/orders \
  -H "Authorization: Bearer $TOKEN"

In Windows PowerShell use curl.exe, put it on one line and write $env:TOKEN.

Why was the request refused?
Did the credential arrive at the application? YES Continue; if not, check proxies stripping headers. 1 NO Is it expired, malformed or for another environment? YES Expect 401: issue or refresh a correct one. 2 NO Does the identity lack the role, scope or ownership? YES Expect 403: grant access or change the request. 3 NO Does the request appear in application logs? YES Trace the permission check that rejected it. 4 NO Look upstream Check firewall, CDN, web server rules and file permissions. Did the credential arrive at the application? 1 IF YES Continue; if not, check proxies stripping headers. NO Is it expired, malformed or for another environment? 2 IF YES Expect 401: issue or refresh a correct one. NO Does the identity lack the role, scope or ownership? 3 IF YES Expect 403: grant access or change the request. NO Does the request appear in application logs? 4 IF YES Trace the permission check that rejected it. NO Look upstream Check firewall, CDN, web server rules and file permissions.

The first step looks backward from the others for a reason: a common bug is a web server or proxy that does not pass the Authorization header through to the application. Another is a redirect to a different host, after which many clients deliberately drop credentials.

For tokens, check expiry, issuer, intended audience and granted scopes. API keys, tokens and OAuth and JSON Web Tokens explain those fields. Avoid pasting live tokens into online decoders or chat tools.

Web server 403s

On Linux, the web server's user needs read permission on the file and execute (search) permission on every directory above it. To see the chain:

namei -l /var/www/site/index.html

Check the error log too. nginx writes messages such as "directory index of ... is forbidden" when there is no index file, and "Permission denied" for filesystem trouble. Security modules such as SELinux can deny access even when ordinary permissions look right.

Grant the minimum needed. Making everything world-writable to clear a 403 creates a far worse problem.

If a firewall or content delivery network produced the refusal, its event log usually shows which rule matched. Adjust that rule narrowly for the legitimate traffic. Web application firewalls covers false positives.

Choosing the code in your own application

Situation Reasonable response
No credentials on a protected API 401 with a challenge
Expired or invalid token 401
Valid user, insufficient role 403
Valid token, missing scope 403
User requests someone else's private record 404 or 403, chosen consistently
Too many attempts 429
Anonymous visitor to a web page needing login Redirect to sign-in

Hiding existence with 404 is permitted by the standard. If you do it, make the response for "not yours" match the one for "does not exist", including its content.

Writing useful error responses

A bare number leaves people guessing. For an API, return a small, consistent body that a developer can act on without learning anything sensitive:

HTTP/1.1 403 Forbidden
Content-Type: application/problem+json

{"title": "Missing permission", "detail": "This action needs the orders:write scope.", "instance": "req-7f3a"}

This follows the problem details format of RFC 9457. The request identifier lets support find the matching log entry.

How much to say depends on who is asking. Naming a missing scope helps a legitimate integrator. Listing which other users can see a record, or which internal rule fired, helps nobody who should not already know.

For web pages, say plainly whether signing in might help. A 403 page that offers "switch account" and "request access" saves many support messages. Show which account is currently signed in, since using the wrong one is such a common cause.

Expired sessions in applications

Single-page applications and mobile apps meet 401 routinely, because short-lived tokens expire by design. Handle it in one place:

  1. On a 401, try to refresh the token once.
  2. If that works, repeat the original request.
  3. If it fails, send the person to sign in, and preserve what they were typing where possible.
  4. Never loop. A refresh that returns 401 should end the attempt.

If many requests fail at once, let them share a single refresh instead of starting dozens. On a 403, do not refresh or sign the user out. Explain the refusal and leave the session alone, because a new token for the same account will normally carry the same rights.

When users report being logged out unexpectedly, check server clocks as well. A server whose time has drifted can reject tokens that are perfectly good. With several servers, also confirm that they all share the same signing keys or session store, or a user will be accepted by one machine and challenged by the next.

Testing your access rules

Access control is easy to get right for the happy path and wrong at the edges, so test the refusals deliberately. Using test accounts on your own system, try each protected route with no credentials, with an expired token, with an ordinary account and with an account that owns different data. Write down the status you expect for each before running it.

Put those cases into your automated tests. A new route that returns 200 to an anonymous request is then caught before release, which is far cheaper than hearing about it from a stranger.

Security habits that matter more than the code

Check on the server. Hiding a button is a convenience, not a control. Anyone can send the request directly.

Check each object. Confirming that someone is a signed-in customer is not enough; confirm that this invoice belongs to that customer. Missing object-level checks are a widespread flaw.

Deny by default. New routes should be inaccessible until a rule allows them.

Keep login errors vague. "Email or password is incorrect" avoids confirming which accounts exist.

Limit guessing. Slow repeated failures and alert on unusual volumes.

Log refusals with enough context to investigate, without recording passwords or full tokens.

What these codes mean for search engines and caches

Crawlers cannot index content behind a 401 or 403. That is correct for private areas and a problem if a firewall rule is turning away legitimate search crawlers from public pages. If pages drop out of results, check your access logs for refused requests from them.

Be careful with caching around access control. A shared cache should never store a signed-in user's page and serve it to others, and a cached 403 can keep refusing someone after access was granted. Mark these responses private or no-store as appropriate. For the broader picture of response codes, see status codes by family.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic