
Quick Answer
A 401 Unauthorized error means the destination did not receive or accept valid authentication credentials for the requested resource. Check the `WWW-Authenticate` response header first, then confirm that the client sent the expected username and password, API token, or session cookie to the correct destination.
The first 401 can be a normal part of HTTP challenge-and-response authentication: the server sends a challenge, and the client retries with credentials. If the client already sent credentials, check their expiration, destination, format, and storage. For time-limited tokens that expose these fields, compare their expiration and not-before values with the clocks on the issuing and receiving systems. A 407 response needs a different fix because it asks for credentials to an HTTP proxy.
Key Takeaways
- A 401 response concerns authentication to the destination website or API.
- A server that generates a 401 must include a `WWW-Authenticate` challenge that identifies at least one accepted authentication scheme.
- Missing, malformed, expired, revoked, or mismatched credentials can all produce 401 responses.
- Cookie-based logins can fail when a session expires or the browser stops sending the required cookie.
- Valid credentials with insufficient permission usually point to 403 Forbidden instead.
- HTTP proxy authentication is separate. An HTTP proxy that requires authentication returns 407 Proxy Authentication Required.
What Does a 401 Unauthorized Error Mean?
A 401 Unauthorized error means the request was not applied because it lacked valid authentication credentials for the target resource. Despite the status name, the immediate question is usually whether the client has authenticated successfully, not whether an authenticated user has enough permission.
RFC 9110 requires a server that generates a 401 response to include at least one challenge in `WWW-Authenticate`. The challenge names an authentication scheme, such as Basic or Bearer. A `realm` identifies the protected area or service for which the credentials apply.
A Basic challenge can look like this:
An API using Bearer tokens can challenge a request that omitted a token:
When a client supplies a Bearer token and the server rejects it, the challenge can add an error such as `error="invalid_token"`. A request with no authentication information normally receives the challenge without that error value. The client can then retry with a new or corrected credential.
This exchange is expected for schemes that wait for a challenge before sending credentials. If the same credentials have already failed, repeating them will not solve the problem. A 401 without `WWW-Authenticate` does not meet the RFC requirement, so identify the server, reverse proxy, API gateway, or application that created the response before changing anything else. When the failing layer is unclear, use the proxy and HTTP error-code reference to distinguish destination authentication from name resolution, connection setup, proxy access, rate limiting, and upstream failures.
401 vs 403 vs 407
HTTP 401 asks the client to authenticate to the destination, 403 indicates that the server refuses the request, and 407 asks the client to authenticate to an HTTP proxy. The response status and challenge header identify which credentials need attention.
| Status | What it usually means | Typical sender | Challenge header | First check |
|---|---|---|---|---|
| 401 Unauthorized | Destination credentials are missing, invalid, expired, or otherwise unacceptable | Origin server, reverse proxy, or API gateway | `WWW-Authenticate` | Destination credentials or session state |
| 403 Forbidden | The request is understood, but the server refuses to fulfill it | Website, API, or intermediary | No authentication challenge is required | Permissions, roles, or resource policy |
| 407 Proxy Authentication Required | The client must authenticate to an HTTP proxy | Forward proxy | `Proxy-Authenticate` | Proxy credentials or access policy |
A valid identity that lacks the required role or scope generally receives 403. Use 403 Forbidden to troubleshoot permission and policy failures, and use 407 Proxy Authentication Required for HTTP proxy credentials, IP allowlisting, and proxy challenges. Some applications use these status codes incorrectly. If the response message conflicts with the status, save the headers and body, identify which component generated them, and check its logs or documentation before changing credentials.
Common Causes of a 401 Unauthorized Error
A 401 response appears when the destination cannot authenticate the request using the credentials or session state it received. The cause may be in the client, the credential itself, or the service responsible for checking it.
| Cause | What to check | Likely correction |
|---|---|---|
| Missing credentials | No `Authorization` field, required API key field, or session cookie reached the protected route | Put the credential in the field documented for that service |
| Incorrect credentials | Username, password, API key, or token does not match the intended account or environment | Recopy or replace the active credential |
| Expired or revoked Bearer token | The challenge reports `invalid_token`, or the API identifies the token as expired or revoked | Use the service's supported refresh or token-issuance flow |
| Wrong authentication scheme | The client sends Basic credentials to a Bearer-only route, or the reverse | Follow an authentication scheme offered by the challenge and supported by the service |
| JWT issued for another service | The issuer, audience, or environment does not match the receiving API | Obtain a token intended for the correct API and environment |
| Expired or missing session | A required session cookie is absent, out of scope, invalidated, or no longer recognized | Sign in again and inspect the site's cookie and session configuration |
| Clock skew | The issuing and receiving systems disagree about whether a time-limited token is valid yet or has expired | Synchronize the relevant clocks and keep any permitted leeway narrow |
| JWT signature failure | The signature cannot be verified with an approved key and algorithm | Check the trusted key set, permitted algorithm, and key-rotation state |
| Server configuration | Authentication middleware, gateway rules, or credential forwarding differs between working and failing routes | Compare both routes and repair the component that handles them differently |
Not every API token is a JWT. When a JWT includes them, the issuer identifies who created it, the audience identifies the intended API, and the expiration and not-before values define when it may be accepted. A successfully verified signature confirms that the signed token data has not changed.
Opaque API keys and tokens do not expose those fields, so check their validity through the service that issued them. The 401 response alone does not show which credential check failed. Start with the challenge and one repeatable request instead of clearing unrelated settings.
Diagnose a 401 Error Safely
Diagnose a 401 by preserving the first response, identifying its authentication challenge, and comparing the failed request with the service's documented authentication requirements. Use an endpoint you own or are authorized to test, and keep live credentials out of screenshots, tickets, and shared logs. The commands below use `api.example.com` as a placeholder. Replace it with the authorized endpoint you are testing. This first command deliberately omits credentials and disables environment-configured proxies so it can capture the destination's challenge directly:
`--disable` prevents cURL from reading its default configuration only when it is the first command-line option, as it is here. `--noproxy "*"` prevents proxy environment variables from changing the route, while the two timeout options stop an unresponsive test. `--dump-header -` writes the response headers to standard output, and `--output /dev/null` discards the body on Unix-like systems. The example uses Bash or Zsh; native Windows shells need their own line-continuation syntax and use `NUL` instead of `/dev/null`.
Read every `WWW-Authenticate` value because a response can offer more than one scheme. If the request contained a rejected Bearer token, the challenge can include `error="invalid_token"`; a request with no authentication information normally omits that error. Response headers can also contain cookies and other sensitive values, so review them before saving or sharing the output. When redirects or authentication exchanges produce several responses, show every response-header block with cURL so an initial 401 is not mistaken for the final response.
Then compare the failed request with the service's authentication requirements:
- Confirm the effective URL, method, hostname, and environment.
- Identify the component that returned 401, such as an API gateway, reverse proxy, application, or API service.
- Record the challenge scheme, realm, non-sensitive `error` value, timestamp, and request identifier.
- Confirm whether the client sent an `Authorization` field, a documented API key field, a session cookie, or no credentials.
- Replace an expired or revoked credential through the service's supported flow.
- Retry once with the corrected credential or client configuration while keeping the route and method unchanged.
In a browser, use the Network panel to select the failed request and inspect its status, request and response headers, response body, cookies, redirects, and initiator. If DevTools does not reveal which layer produced the failure, use this comparison of browser debugging tools to choose another diagnostic method. Do not copy an `Authorization` value, session cookie, API key, or full request export into a public issue.
DNS flushing is not a normal 401 fix. An HTTP service has already answered the request, and changing DNS cannot make rejected credentials valid.
6 Ways to Fix a 401 Unauthorized Error
Use the authentication scheme in `WWW-Authenticate` to choose the relevant fix. Change one credential or configuration item at a time so the next response shows whether that change worked.
Confirm the Protected URL and Authentication Scheme
Check the complete URL, hostname, API version, and environment before changing a password or token. Development and production endpoints can trust different identity systems, and two routes on the same host can use different authentication rules. Compare `WWW-Authenticate` with the client configuration and send Basic credentials only when the service offers or documents Basic authentication.
RFC 7617 defines the Basic credential sequence: join the user ID and password with a colon, convert that value to bytes using the expected character encoding, and encode those bytes with Base64. Basic credentials should be sent only over HTTPS because Base64 is not encryption and does not protect them in transit.
For an interactive Basic authentication test, let cURL prompt for the password instead of placing it in the command:
This command is relevant only when the target supports Basic authentication. Do not force Basic when the service requires Bearer, Digest, Negotiate, or a custom authentication flow.
Supply Credentials Through the Correct Client Setting
Put the credential where the service expects it. HTTP challenge credentials normally use `Authorization`; an API key may use `Authorization` or a named custom field; and a website login can create a session cookie for later requests. The `WWW-Authenticate` response is the server's challenge, not a place where the client sends credentials. Check for a missing `Bearer` prefix, whitespace copied with a token, an incorrect API key field name, or a credential loaded from the wrong secret store. Keep secrets out of URLs because URLs can enter browser history, access logs, analytics, and referrer data.
Redirects deserve attention. A client may intentionally withhold destination credentials when a redirect crosses to another origin. Inspect the first response and every `Location` value before allowing a secret to follow another hostname, scheme, or port. To reproduce the request without exposing its secret, review how to send request headers with cURL and keep automatic redirects disabled until the destination is verified.
Replace Expired, Revoked, or Invalid Tokens
Use the service's supported refresh, sign-in, or token-issuance flow when a token has expired or been revoked. Do not keep replaying the old token, and do not send a refresh token as though it were an access token. RFC 6750 recommends 401 with `invalid_token` when a supplied Bearer token is expired, revoked, malformed, or otherwise invalid. A request with no authentication information should not receive that error value.
Bearer tokens must be protected with TLS. Confirm that a replacement token is meant for the correct API and environment and, where applicable, the expected application and user. If it is a JWT, also validate any issuer and audience claims required by the service. Never paste a live token into an online decoder or troubleshooting post.
Repair Cookie and Session Authentication
Sign in again through the website's current login flow when the application uses a session cookie. The browser may have no cookie to send, the server-side session may have expired, or the cookie may fall outside its allowed domain, path, `Secure`, or `SameSite` conditions.
Open a private window, complete a fresh login there, and repeat the failed action. If that session works, compare the affected site's cookies and stored application state with the ordinary profile. Private browsing does not guarantee that every extension is disabled, so check extension behavior separately if it could affect the request. Delete only the affected site's cookies when a clean sign-in is necessary instead of erasing all browser data by default. The differences between session and persistent cookies, along with the `Secure`, `HttpOnly`, and `SameSite` attributes, are covered in how browser cookies work.
Server owners should verify that a successful login creates the intended session. When the application uses server-side sessions, they should also confirm that the session store remains available and that logout or expiration invalidates the matching entry.
Correct Clock and Token-Validation Problems
Synchronize the clocks on services that issue and verify time-limited tokens. Clock skew can make one system treat a token as expired while another still considers it valid. When present in a JWT, `exp` sets the expiration time, while `nbf` states when the token can first be accepted. RFC 7519 allows a small amount of leeway for these checks. Keep it narrow and consistent rather than disabling expiration checks.
Time is only one JWT validation input. Verify the signature with a trusted key and an allowed signing algorithm, then check the expected issuer and audience. During key rotation, keep each trusted verification key available for as long as the system's security policy requires it to validate tokens that are still meant to be accepted.
Fix Authentication and Reverse-Proxy Configuration
Compare a working route with the failing route on the same deployment. Check whether the reverse proxy forwards `Authorization`, whether authentication middleware runs in the intended order, and whether both routes use the same session store or identity service. Next, review the route rules, cookie settings, trusted token issuers, verification keys, account state, and identity-service health. Use request identifiers to match reverse-proxy and application logs without recording credentials.
When the failure happens only in a browser, inspect any `OPTIONS` request sent before the cross-origin request. The Fetch standard excludes user credentials from a CORS preflight. Authentication middleware that rejects the preflight with 401 can therefore stop the browser from sending the authenticated request. Apply the site's intended CORS rules to the preflight, then authenticate the request that follows.
A server that generates 401 must return an accurate `WWW-Authenticate` challenge. If it has accepted the identity but refuses access because of a role, scope, or resource rule, 403 is usually the clearer response. That distinction tells the client whether to change its credentials or its permissions.
Fixing 401 Errors in APIs
Fix an API 401 by supplying a missing credential through the documented field, matching the endpoint's authentication scheme, or replacing a credential the service no longer accepts. Keep authentication failures separate from malformed requests, permission failures, and rate limits.
For a Bearer token request, cURL 8.3.0 or later can import an `API_TOKEN` environment variable and expand it internally. The official cURL variable documentation describes this feature. The token must already be set by the application's secret manager or runtime configuration:
This form keeps the token text out of the command arguments supplied by the shell. Environment variables still need process-level protection, and response diagnostics can contain other sensitive details. Redact retained output and remove the variable from the environment when the test is complete.
Use this order when the API still returns 401:
- Check that the token or API key reached the field documented for that endpoint.
- Verify that the credential is active and belongs to the correct API environment.
- For a JWT, verify its signature with a trusted key and permitted algorithm, then validate the claims required by the service, which may include issuer, audience, `exp`, and `nbf`.
- Check the challenge and response body for a machine-readable error that does not expose secrets.
- Confirm the client did not lose credentials during a cross-origin redirect.
- Obtain one replacement credential through the supported flow. If a request using the replacement receives the same response, stop retrying and inspect the server-side authentication and route configuration.
A malformed request can return 400 Bad Request, while a valid identity without the required permission can return 403. A request sent with the wrong method can return 405 Method Not Allowed, and excessive request volume can produce 429 Too Many Requests. Diagnose the actual status instead of treating every failed API call as an authentication problem.
Fixing 401 Errors in Browsers
Browser 401 errors usually come from a failed website session or an HTTP authentication challenge. A form-based login commonly creates a session cookie. Basic and other HTTP schemes can instead trigger a browser credential prompt after the server sends `WWW-Authenticate`.
Start with these checks:
- Open the protected page through the site's current navigation instead of an old bookmark.
- If the site uses a login form, sign out and sign back in once with the intended account.
- If the browser displays an HTTP authentication prompt, confirm the requested realm before entering the matching credentials.
- Open a private window, sign in again, and repeat the same action.
- If the private session works, remove the affected site's cookies and repeat a clean login in the ordinary profile.
- Use DevTools to check whether the failed request sent the expected cookie or `Authorization` field.
- Record the page address, time, action, and any request identifier before contacting support.
Do not repeatedly submit passwords or clear unrelated system caches. If the same 401 appears across several accounts and devices after a deployment, the website owner should inspect the authentication service and route configuration.
401 Errors When a Proxy Is Configured
A 401 received through a proxy normally means the destination website or API rejected destination authentication. The proxy can relay that response, but changing the exit IP does not repair a missing login, expired API token, or invalid session cookie.
An HTTP proxy that requires authentication returns 407 with `Proxy-Authenticate`. The client replies with proxy credentials in `Proxy-Authorization`. HTTP destination credentials normally use `Authorization`, while a service-specific API key may use another documented field. In cURL, `--proxy-user` supplies proxy credentials and `--user` supplies destination credentials. Keep them separate so a proxy secret is not sent to the destination. SOCKS authentication uses the SOCKS protocol rather than HTTP status 407.
When proxy routing is part of the test, configure cURL with a proxy and keep its credentials separate from destination authentication. Troubleshoot destination credentials for 401 and HTTP proxy credentials or IP allowlisting for 407. During an authorized test, keep the same proxy session while changing authentication so an IP change does not introduce another variable. Proxidize can supply the network route, but it cannot grant access to a protected resource.
Fixes That Waste Time or Weaken Security
Broad changes can remove evidence or weaken security without addressing authentication. Start with the destination's challenge and the authentication state it received, including whether a credential was absent. Do not reset the browser or network in ways that discard useful evidence.
| Action | Why it is a poor default fix | Better approach |
|---|---|---|
| Flush DNS | DNS resolution does not supply destination credentials | Inspect `WWW-Authenticate` and the request's authentication state |
| Rotate proxy exits | A new IP does not renew a login, token, or session | Keep the route stable while correcting destination authentication |
| Disable TLS verification | This weakens identity checks without making credentials valid | Correct certificates and authentication as separate issues |
| Retry the same token repeatedly | An expired or revoked token remains invalid | Renew or reauthorize once through the supported flow |
| Clear all browser data immediately | This destroys useful state and signs the user out of unrelated sites | Compare a private window, then remove only the affected site's data if needed |
| Share a verbose trace without review | Traces can contain tokens, cookies, and account details | Redact secrets and retain only the evidence needed for diagnosis |
Certificate verification and authentication are separate checks. Repair trust problems with safe cURL certificate troubleshooting instead of leaving verification disabled. If the requested resource does not exist, troubleshoot the 404 Not Found response instead of changing credentials.
Preventing 401 Errors
Prevent avoidable 401 errors by tracking credential lifetimes, testing session behavior, synchronizing clocks, and checking authentication after configuration changes. Clients need a defined renewal process, while servers need consistent rules across every server component that handles the request.
For API clients:
- Store credentials in an approved secret manager and load them only at runtime.
- Track expiration without logging token contents.
- Refresh or reauthorize before a credential becomes unusable when the service supports it.
- Stop automatic retries after an authentication failure until the credential, client configuration, or server authentication state changes.
- Test redirect behavior and keep destination and proxy credentials separate.
For service owners:
- Test protected and public routes after authentication or gateway changes.
- Monitor 401 rates by route, deployment, authentication scheme, and failure reason without recording secrets.
- Keep server clocks synchronized and plan signing-key rotation.
- Return the required `WWW-Authenticate` challenge without exposing sensitive account details.
- Correlate gateway, identity-service, and application logs with request identifiers rather than secrets.
- Use 403 for authenticated requests that fail an authorization rule when that distinction fits the application.
Frequently asked questions
A 401 occurs when a protected resource does not receive acceptable authentication. Common causes include missing credentials, an incorrect password, an expired or revoked token, a missing session cookie, a token issued for another audience, or a server component that fails to forward or validate authentication correctly.
For a form-based login, open the site's current login page and sign in again with the intended account. For a browser HTTP authentication prompt, verify the realm and enter the credentials assigned to that protected area. If the problem continues, test a fresh login in a private window, inspect the failed request in DevTools, and remove only that site's cookies if necessary.
Inspect `WWW-Authenticate`, confirm the expected authentication scheme, and verify that the token or API key reached the documented field. Replace an expired or revoked credential through the supported flow. If the service uses JWTs, verify the signature and the claims it requires, such as issuer, audience, expiration, or not-before time, before checking redirects and server logs.
The password may belong to another account, realm, hostname, or environment, or the service may expect a token or session instead of Basic authentication. A disabled account, failed identity service, stale session, clock problem, or server authentication configuration error can also reject otherwise correct input.
HTTP 401 means the destination did not accept valid authentication, and a server generating that response must provide a `WWW-Authenticate` challenge. HTTP 403 means the server understood the request but refuses it; valid credentials with insufficient permission commonly lead to 403 rather than another 401.
HTTP 401 concerns authentication to the destination website or API and uses `WWW-Authenticate`. HTTP 407 concerns authentication to an HTTP proxy and uses `Proxy-Authenticate`; the client then supplies credentials in `Proxy-Authorization`.
HTTP classifies 401 as a 4xx client-error response, but the root cause can still be server-side. A client may omit or send invalid credentials, while a gateway, authentication service, session store, clock, or route configuration may reject credentials incorrectly.
No, not when the destination is rejecting authentication. A proxy can change the network route for an authorized test, but it cannot renew a token, restore a session, or grant permission. An HTTP proxy that requires authentication returns 407; SOCKS proxy authentication follows the SOCKS protocol instead.