1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
401 vs 403: unauthorized vs forbidden, and when to use each

Key takeaways

  • 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-Authenticate header.
  • 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 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-Authenticate header 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-Authenticate on 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →