401 Response Code: What It Means and How to Fix It

401 Response Code

You loaded a page, called an API, or ran a script. Instead of data, you got 401 Unauthorized. The server is telling you it doesn’t know who you are, or doesn’t believe you.

This guide explains what a 401 response code actually means, why it shows up, and how to fix it whether you’re a visitor, a developer, or a site owner.

What Is a 401 Response Code?

A 401 response code is an HTTP status code meaning the request lacks valid authentication credentials for the target resource. The server understood the request. It refuses to fulfill it until you prove your identity.

The official name is “401 Unauthorized,” which is a bit misleading. The code is really about authentication (who you are), not authorization (what you’re allowed to do). The HTTP specification (RFC 9110) defines it as a failure of credentials, and the server must include a WWW-Authenticate header that tells the client which authentication scheme to use.

You’ll see it written many ways:

  • 401 Unauthorized
  • HTTP Error 401
  • 401 Authorization Required
  • Access Denied
  • Error 401 – Invalid Credentials

All of them mean the same thing: the server needs valid credentials and didn’t get them.

401 vs. 403: The Difference That Trips Everyone Up

These two codes get confused constantly. The distinction matters because the fix is completely different.

Feature401 Unauthorized403 Forbidden
Core meaning“I don’t know who you are”“I know who you are, and you can’t come in”
Problem typeAuthenticationAuthorization (permissions)
Will re-authenticating help?Often, yesUsually no
Required headerWWW-AuthenticateNone required
Typical causeMissing, expired, or wrong credentialsValid login but insufficient role or blocked IP
Common fixLog in again, refresh token, correct API keyRequest access from an admin, change permissions

A quick mental test: if logging in with the right account could solve it, you’re probably looking at a 401. If you’re already logged in and still blocked, think 403.

One real-world wrinkle: some servers return 404 instead of 403 to hide that a resource exists at all. That’s a deliberate security choice, not a bug.

Common Causes of a 401 Error

Missing credentials. The request arrived with no username, password, token, or API key. This is the most common cause in API work.

Wrong credentials. A typo, an outdated password, or a key copied from the wrong environment (staging vs. production).

Expired tokens or sessions. JWTs and OAuth access tokens have short lifespans, often 15 minutes to an hour. When they expire, the next request gets a 401.

Malformed authorization header. Sending Authorization: <token> instead of Authorization: Bearer <token> is a classic mistake. Stray whitespace and missing prefixes cause failures too.

Clock drift. Token validation depends on timestamps. If your server or device clock is off by several minutes, perfectly valid tokens can be rejected as expired or “not yet valid.”

Revoked or rotated keys. Someone regenerated the API key, deleted the user, or rotated a secret, and your app is still using the old one.

Cached or stale browser data. Old cookies or cached credentials can send outdated authentication to the server.

Server-side misconfiguration. Broken .htaccess rules, wrong auth middleware order, or a reverse proxy stripping the Authorization header can cause 401s even with correct credentials.

How to Fix a 401 Response Code as a Website Visitor

Start with the simple stuff before assuming something is broken.

Checklist:

  • [ ] Double-check the URL. Some pages that require login return 401 when you land on them directly.
  • [ ] Log out completely, then log back in.
  • [ ] Re-enter your username and password carefully. Check Caps Lock.
  • [ ] Clear your browser cache and cookies for that site.
  • [ ] Try a private/incognito window to rule out extensions or stale cookies.
  • [ ] Disable browser extensions that modify headers, such as ad blockers or privacy tools.
  • [ ] Try another browser or device.
  • [ ] Reset your password if you’re unsure it’s correct.
  • [ ] Check whether your account is active, suspended, or expired.

If none of that works, the problem is likely on the site’s side. Contact support and include the exact URL, the time of the error, and what you were doing.

How to Fix a 401 Error as a Developer

This is where most searches for “401 response code” come from. Work through these in order.

Step 1: Inspect the Raw Request and Response

Don’t guess. Look at what’s actually being sent. Use your browser’s Network tab, or reproduce the call with cURL:

curl -i -H “Authorization: Bearer YOUR_TOKEN” https://api.example.com/v1/users

The -i flag shows response headers. Look for the WWW-Authenticate header in the response. It often names the scheme (Bearer, Basic) and sometimes includes an error field such as invalid_token or expired_token. That one line can save you an hour.

Step 2: Verify the Authorization Header Format

Common valid formats:

SchemeHeader Format
BasicAuthorization: Basic base64(username:password)
Bearer (OAuth 2.0 / JWT)Authorization: Bearer <access_token>
API key (header)X-API-Key: <key> (varies by provider)
DigestAuthorization: Digest username=”…”, realm=”…”, …

Check the API documentation for the exact header name. Providers differ, and a wrong header name looks identical to missing credentials.

Step 3: Check Token Expiration

If you use JWTs, decode the token (jwt.io works for non-sensitive tokens) and check the exp claim. Compare it to the current Unix timestamp.

If it’s expired, request a new one with your refresh token. Build this into your app so it refreshes automatically on a 401 and retries the request once.

Step 4: Confirm You’re Using the Right Environment

Sandbox and production credentials are usually separate. A test key sent to a production endpoint returns a 401 every time. Check the base URL and the key’s environment together.

Step 5: Watch for Proxies and Redirects

Some redirects drop the Authorization header for security reasons. If your request hits a 301 or 302 and then fails with 401, the redirect may have stripped your credentials. Call the final URL directly.

Reverse proxies and CDNs can also strip headers. Check your Nginx, Apache, or load balancer config.

Step 6: Sync Your Clocks

If tokens look valid but get rejected, compare server time against a reliable source. Enable NTP sync on servers and containers.

How to Fix a 401 Error on Your Own Website (Site Owners)

If visitors report 401 errors on your WordPress or custom site, check these areas.

Password-protected directories. A misconfigured .htpasswd or .htaccess file triggers 401 prompts. Verify the file path in your AuthUserFile directive is correct and the file is readable by the web server.

Security plugins. WordPress security plugins sometimes lock out legitimate users after failed login attempts or block wp-login.php and the REST API. Temporarily deactivate them to test.

Hosting-level protection. Staging environments on many hosts are password-protected by default. If a staging site’s protection leaked into production, visitors get 401s.

Broken authentication middleware. In frameworks like Express, Django, Laravel, or Spring, check the order of middleware. Authentication must run before the routes it protects, and public routes need to be explicitly excluded.

REST API and plugin conflicts. Some plugins require authentication on endpoints your front end calls publicly. Check your browser console for 401s on /wp-json/ calls.

Search engine impact. If Googlebot gets a 401 on pages you want indexed, those pages won’t appear in search. Google treats 401 pages as inaccessible. Check Google Search Console’s page indexing report for affected URLs.

See More: Co Development Software: Tools, Models & Setup Guide

Best Practices for Returning 401 Responses (For API Designers)

Returning 401 correctly makes your API easier to use and safer.

Do:

  • Include a WWW-Authenticate header with the correct scheme.
  • Return a clear, consistent JSON error body (for example, an error code and a human-readable message).
  • Distinguish “expired token” from “invalid token” so clients know whether to refresh or re-authenticate.
  • Rate-limit authentication attempts to slow brute-force attacks.
  • Log failed authentication attempts for monitoring.

Don’t:

  • Reveal whether a username exists. “Invalid username or password” is safer than “User not found.”
  • Return 401 when you mean 403. Mixing them up confuses client developers and breaks retry logic.
  • Return a 200 status with an error message in the body. It breaks monitoring and client libraries.
  • Leak stack traces or internal details in the error response.

Pros and Cons of Common Authentication Methods

MethodProsCons
Basic AuthSimple, universally supportedCredentials sent on every request; must use HTTPS
API KeysEasy to issue and revokeNo built-in expiry; easy to leak in code repos
Bearer/JWTStateless, scalable, supports expiryHard to revoke before expiry; larger payloads
OAuth 2.0Delegated access, scoped permissionsMore complex to implement correctly
Session CookiesFamiliar, easy for browsersVulnerable to CSRF without safeguards; stateful

Real-World Troubleshooting Scenarios

Scenario 1: The API worked yesterday. Almost always an expired token or rotated key. Check your provider’s dashboard for key status first.

Scenario 2: It works in Postman but fails in code. Compare the raw headers. Your code may be sending an extra space, a missing Bearer prefix, or a different header casing handled badly by a proxy. Log the exact request your code sends.

Scenario 3: Intermittent 401s. Think load balancers and clock drift. If requests hit multiple servers and only some reject the token, one server may have an outdated secret or a skewed clock.

Scenario 4: 401 only after redirect. The redirect dropped your authorization header. Update the URL to the final destination.

Security Notes You Shouldn’t Skip

  • Always use HTTPS. Basic Auth and bearer tokens over plain HTTP expose credentials to anyone on the network.
  • Never hardcode secrets in front-end code or public repositories. Use environment variables or a secrets manager.
  • Rotate credentials when someone leaves a team or a key may have leaked.
  • Don’t paste live tokens into online decoders or public forums. Use expired or test tokens for debugging.

Frequently Asked Questions

What does a 401 response code mean?

It means the server couldn’t verify who you are. Your request had no credentials, or the ones you sent were wrong or expired. The server is asking you to authenticate first.

How do I resolve a 401 error?

  • Visitors: log out and back in, clear cookies and cache, and check your password.
  • Developers: check the Authorization header format (for example, Bearer <token>), refresh expired tokens, and confirm you’re using the right environment’s key.
  • Site owners: review .htaccess rules, security plugins, and auth middleware.

What do 401 and 403 mean?

  • 401 Unauthorized: “I don’t know who you are.” Logging in correctly can fix it.
  • 403 Forbidden: “I know who you are, but you’re not allowed in.” A new login usually won’t help unless that account has more permissions.

What do 200, 201, 400, 401, 404, and 500 signify?

CodeMeaningIn plain terms
200 OKRequest succeededEverything worked
201 CreatedA new resource was createdYour POST saved something new
400 Bad RequestMalformed or invalid requestThe server can’t understand what you sent
401 UnauthorizedMissing or invalid credentialsPlease prove who you are
404 Not FoundResource doesn’t exist at that URLWrong or removed address
500 Internal Server ErrorServer failed unexpectedlyThe problem is on the server, not you

Quick memory trick: 2xx means success, 4xx means the client made a mistake, and 5xx means the server did.

See More: Dragon Medical Dictation Software: Is It Worth It?

About: admin