Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

A 401 Unauthorized response means the server could not authenticate your request: credentials were missing, rejected, expired, malformed, or sent in the wrong way. Start by reading the response’s WWW-Authenticate header, then send a valid credential using the scheme it names. If the server already recognizes you but will not let you perform an action, the problem is usually 403 Forbidden, not 401.

What a 401 Unauthorized response means

HTTP 401 is an authentication failure. The requested resource requires an identity, but the server did not receive valid credentials for it. MDN defines it as a response indicating that a request was not successful because it lacks valid authentication credentials for the requested resource.

The response normally includes a WWW-Authenticate header. That header advertises the authentication challenge and identifies one or more schemes the client may use. The scheme might be Basic, Bearer, Digest, or another method supported by the service. Do not automatically add a bearer token unless the endpoint actually requires bearer authentication.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I fix a 401 Unauthorized error?

  1. Inspect the complete response. Record the status, response body, and every WWW-Authenticate header. The challenge often tells you which scheme and parameters the server expects.
  2. Confirm that credentials were sent. In an API client, inspect the outgoing request and verify that authentication is present in the expected header, cookie, query parameter, or request body. Most HTTP APIs use the Authorization header, but the service documentation is authoritative.
  3. Validate the credential. Check that the key, password, session cookie, or access token belongs to the intended account and environment, has not expired, and has not been revoked. Never paste live secrets into tickets, shell history, CI logs, or public posts.
  4. Match the required format exactly. A valid secret in the wrong scheme still fails. For example, bearer authentication requires the scheme name followed by the access token, while Basic authentication requires a base64-encoded username-and-password pair. Do not add quotation marks, a second prefix, or unintended whitespace.
  5. Check the target host and path. Make sure the request is going to the intended API hostname, tenant, version, and resource. A token issued for one audience or environment may be rejected by another.
  6. Separate authentication from permission. Once the server accepts your identity, a missing role, scope, or resource permission generally produces 403. Repeating login attempts will not solve a permission failure.
  7. Use the service’s diagnostics. Identity providers and frameworks often log a more specific reason, such as an expired token, invalid audience, missing scope, or signature failure. Enable only the logging needed to diagnose the request and redact credentials.

Why am I getting a 401 error?

No credential reached the server

Reverse proxies, redirects, browser extensions, CORS-related client code, and incorrectly named headers can remove or prevent authentication. Capture the request at the client and, where permitted, at the gateway. Confirm the final request—not just the first URL—contains the credential.

The token or key is invalid

An access token can be expired, revoked, signed by the wrong issuer, intended for another audience, or copied with a missing character. API keys can be disabled or restricted to different hosts. Generate or retrieve a fresh credential through the provider’s documented process, then test it against the correct environment.

The authentication scheme is wrong

The WWW-Authenticate challenge is the best starting point. A server that challenges with Basic will not interpret a bearer token as a Basic credential, and a Digest challenge requires a calculated response rather than a plain password. Follow the scheme’s protocol and the endpoint documentation.

Cookies or browser sessions are stale

For a website, sign out, remove the site’s cookies, close existing tabs, and sign in again. If the site uses multiple subdomains, check that the session cookie is scoped to the host receiving the request. A private window can distinguish a stale local session from an account or server problem.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A redirect changes the request context

When a URL redirects to another host, a client may deliberately avoid forwarding an Authorization header. Use the final documented endpoint, inspect redirect behavior, and never forward credentials to an untrusted domain.

How do I fix a 401 error in an API request?

For an API, reduce the request to a safe, reproducible call and compare it with the provider’s authentication example. Replace real secrets with environment variables while debugging.

Bearer-token example with cURL

curl -i https://api.example.com/v1/resource 
  -H "Authorization: Bearer $ACCESS_TOKEN" 
  -H "Accept: application/json"

Check the returned challenge and body. If the provider returns an invalid-token indication, obtain a new access token and verify its audience, issuer, expiry, and scopes according to that provider.

Basic-authentication example with cURL

curl -i -u "$API_USER:$API_PASSWORD" 
  -H "Accept: application/json" 
  https://api.example.com/v1/resource

Use Basic only over HTTPS and only when the service requires it. The client constructs the correct header; do not hand-edit a base64 string unless the API documentation explicitly requires that workflow.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python request

import os
import requests

url = "https://api.example.com/v1/resource"
headers = {
    "Authorization": f"Bearer {os.environ['ACCESS_TOKEN']}",
    "Accept": "application/json",
}
response = requests.get(url, headers=headers, timeout=30)
print(response.status_code)
print(response.headers.get("WWW-Authenticate"))
print(response.text[:1000])

A 401 from this code means the server rejected authentication, not that Python failed generally. Compare the exact URL, header spelling, token value, and response challenge with a known-good example.

Rank #3
Sale
HTTP: The Definitive Guide
  • Used Book in Good Condition

Node.js request

const token = process.env.ACCESS_TOKEN;
const res = await fetch('https://api.example.com/v1/resource', {
  headers: {
    Authorization: `Bearer ${token}`,
    Accept: 'application/json'
  }
});
console.log(res.status, res.headers.get('www-authenticate'));
console.log(await res.text());

Bearer-token checks based on RFC 6750

Bearer tokens are accepted by whoever possesses them, so protect them as secrets. Send the token in the Authorization: Bearer header unless the resource server documents another permitted method. RFC 6750 describes invalid-token handling and 401 responses, but a 401 alone does not identify whether the token was omitted, expired, malformed, revoked, or otherwise rejected.

  • Confirm the access token is meant for the resource server’s audience.
  • Check its expiry and refresh it through the identity provider when necessary.
  • Verify that the token has not been revoked and that its signing key or issuer is trusted.
  • Request the scopes required by the specific endpoint.
  • Ensure your HTTP client has not encoded, trimmed, or replaced the token.

Do not put bearer tokens in URLs: URLs are commonly recorded in browser history, proxies, analytics, and server logs.

401 versus 403: choose the right fix

Response What the server generally knows Next check
401 Unauthorized Credentials are absent, invalid, or not acceptable for the resource. Read WWW-Authenticate; correct the scheme, credential, endpoint, or token state.
403 Forbidden Credentials were accepted, but the identity is not permitted to perform the action. Check account role, token scope, tenant membership, and resource permissions.

Implementations can vary, but this distinction prevents an endless cycle of changing passwords when the account simply lacks authorization.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Microsoft Entra ID and ASP.NET Core Web API

This diagnostic path applies specifically to ASP.NET Core APIs protected with Microsoft Entra ID. Microsoft’s guidance recommends using JwtBearerEvents to capture detailed authentication logs. Configure it in the API’s JWT bearer authentication registration, reproduce one failing request, and inspect the server log for issuer, audience, signature, expiry, or scope details.

Rank #4
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =>
            {
                var logger = context.HttpContext.RequestServices
                    .GetRequiredService<ILoggerFactory>()
                    .CreateLogger("JwtBearerDiagnostics");
                logger.LogWarning(context.Exception,
                    "JWT authentication failed for {Path}",
                    context.Request.Path);
                return Task.CompletedTask;
            },
            OnChallenge = context =>
            {
                var logger = context.HttpContext.RequestServices
                    .GetRequiredService<ILoggerFactory>()
                    .CreateLogger("JwtBearerDiagnostics");
                logger.LogInformation("JWT challenge: {Error} {Description}",
                    context.Error, context.ErrorDescription);
                return Task.CompletedTask;
            }
        };
    });

Do not expose token contents in these logs. Remove verbose diagnostics or restrict them before deploying to production. This event configuration is not a universal fix for browser logins, Basic authentication, or non-.NET stacks.

Website and browser troubleshooting

  1. Reload the page once and check whether the site is asking you to sign in.
  2. Sign out, clear cookies for the affected domain, restart the browser, and sign in again.
  3. Disable extensions that rewrite headers, block scripts, or manage cookies; test in a private window.
  4. Verify your computer’s clock and timezone. Time-based sessions and signed tokens can fail when the clock is substantially wrong.
  5. Check whether the account is locked, the password was changed, or the site requires a separate organization login.
  6. If only one page fails, compare its URL and host with a page that works. The account may be authenticated but lack access to that resource.

Common errors and precise fixes

Symptom Likely cause Fix
401 with no Authorization header sent Client configuration or middleware removed it. Set the header in the request actually sent and inspect redirects.
401 after deploying Production secret, issuer, audience, or environment differs from development. Compare non-secret configuration values and rotate the production credential if exposed.
401 immediately after token refresh The refreshed token was not stored or the old token is still being used. Log a token identifier and expiry—not the token itself—and verify the refreshed value reaches the request.
401 only for one endpoint That route requires a different scheme, scope, audience, or cookie. Read its challenge and documentation separately; do not assume global API settings apply.
Browser works but script fails The browser supplies cookies, CSRF values, or a negotiated login that the script lacks. Use the documented API authentication flow rather than copying browser session secrets.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and security notes

  • Authenticate before retrying. Blind retries with an expired credential add load and cannot succeed.
  • Refresh a token once when the provider supports refresh tokens, then retry the original request once. Stop and surface the error if the refreshed credential also receives 401.
  • Use short, bounded timeouts and preserve the response body and challenge in diagnostic records after removing secrets.
  • Keep credentials in a secret manager or environment injection, rotate them after accidental exposure, and grant the narrowest scopes practical.
  • Test authentication against a staging tenant or harmless read-only endpoint before changing production permissions.

Or skip the browser setup

If your goal is to capture an authenticated or public page rather than debug its login flow, ScreenshotNeo provides a website screenshot API and MCP server. A single request returns a PNG, JPEG, WebP, or PDF. Its cleaner accepts cookie banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing result.

Use the ScreenshotNeo API documentation for authentication and options. The same call can be made from common clients:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. Options include full-page and selector captures, device presets, retina scale, dark mode, PDF paper settings, custom CSS and JavaScript, clicks, waits, blocked resources, headers, cookies, user agents, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, async webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to start.

Frequently Asked Questions

Can a firewall cause a 401 response?

A firewall or proxy can alter, remove, or route an authentication header, although the 401 is generated by the server that receives the resulting request. Compare the request before and after the proxy and inspect its authentication policy.

Should I keep retrying a request that returns 401?

No. Correct or refresh the credential first. Repeating an unchanged request cannot authenticate and may trigger rate limits or account lockout.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does my token look valid but still fail?

Visual validity is not enough. The resource server may reject its issuer, audience, signature, expiry, revocation state, or scopes. Its challenge and server-side diagnostics identify which property needs attention.

Quick Recap

SaleBestseller No. 3
HTTP: The Definitive Guide
HTTP: The Definitive Guide
Used Book in Good Condition
$26.04
SaleBestseller No. 4
HTTP Pocket Reference: Hypertext Transfer Protocol
HTTP Pocket Reference: Hypertext Transfer Protocol
Used Book in Good Condition
$6.94
Bestseller No. 5

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.