---
title: "401 Unauthorized when scraping: your key or login was refused"
description: "401 Unauthorized means the server did not accept your login: a missing, wrong or expired API key, token or cookie. What it means and how to fix it."
url: "https://scrapenews.com/errors/401-unauthorized"
updated: "2026-11-26T00:00:00Z"
---

# 401 Unauthorized when scraping: your key or login was refused

HTTP status codes · 401

Published 26 Nov 2026

What you see

- `401 Unauthorized`
- `HTTP/1.1 401 Unauthorized`
- `401 Client Error: Unauthorized for url`
- `Request failed with status code 401`

**More error strings (8)**

- `Unauthorized: Invalid token`
- `Unauthorized request, please make sure your API key is valid.`
- `Invalid API key`
- `Invalid token`
- `User authentication is required`
- `Auth method is not supported`
- `AUTH001 API Key Missing`
- `WWW-Authenticate: Bearer error="invalid_token"`

## What it means

401 Unauthorized means the server wants to know who you are. You sent no login, or one it does not accept: a missing, wrong or expired key, token or cookie. Sending the same request again won’t help. Fix the login first.

“Unauthorized” is a slightly odd name. The standard (RFC 9110) defines 401 as a request that “lacks valid authentication credentials”. So the problem is not what you may do. The server simply doesn’t know who you actually are.

Two things can happen here:

- **You didn’t send a login.** Send one.
- **You sent one.** Then the 401 means the server refused that login. Trying again only helps with a fresh or different credential.

The server must also say which kind of login it wants, using a `WWW-Authenticate` header. Scraping APIs mostly use an API key: one long secret string that is tied to your whole account. A Bearer token works like a concert wristband. Whoever holds it gets in, no other proof needed (RFC 6750).

## Why it happens

First find out who said no, since a 401 comes from one of two places:

- **Your scraping API** (ZenRows, ScraperAPI, Firecrawl, Bright Data…) does not accept **your API key**. The body carries the vendor’s error.
- **The target site** wants a login, and your session or token is gone. The vendor just passes its reply along to you.

Here are the usual causes, most common first:

1. **No key reached the server.** An empty environment variable, or a header your code never set; ZenRows calls this `AUTH001`. Bright Data says `User authentication is required`. Firecrawl even answers 401 to an `Authorization` header that carries an empty token.
2. **The key is typed wrong.** A missing character, an extra space or a broken string join. ZenRows calls this `AUTH002`.
3. **The key got revoked or regenerated.** The old one stops working. ZenRows answers: `AUTH003`. Firecrawl: `Unauthorized: Invalid token`.
4. **The key is in the wrong place.** Each vendor wants it somewhere else (table in Dev details). ZenRows Batch, for example, takes it only as an `X-API-Key` header, not in the URL.
5. **The header has the wrong shape.** Bright Data refuses a bare key, `Token <key>`, lowercase `bearer` or even two spaces after `Bearer`. Basic auth gets `Credentials are invalid` there.
6. **Your token expired.** OAuth tokens (short-lived keys from a login) run out of time. The server then says `invalid_token` (RFC 6750).
7. **Your login cookie ran out.** Behind a site login, your session lives in a cookie. A cookie with `Expires` or `Max-Age` is deleted after that time and no longer sent (MDN). The site suddenly sees a stranger.
8. **Your IP is not on the allowlist for the key.** Scrapfly answers 401 when a project only allows certain client IPs and yours is not one of them.

Not every vendor uses 401 for money problems. Out of credits, ScraperAPI answers 403, ZenRows and Firecrawl answer 402. One exception: ZenRows Batch sends 401 `subscription_inactive` when a valid key’s subscription needs a billing fix.

Python requests has a couple of quiet traps of its own:

- It removes the `Authorization` header if a redirect sends you to another host.
- An `Authorization` you set through `headers=` is overridden by a `.netrc` file, and `.netrc` by `auth=`.

How 401 differs from each of its neighbours:

| code | who says no | what it means | page |
| --- | --- | --- | --- |
| 401 | the server you called | “Who are you?” No valid login | this one |
| 403 | the server you called | “I know, and still no.” A better login may not help | [403 Forbidden](https://scrapenews.com/errors/403-forbidden.md) |
| 407 | the proxy in between | “Log in to me first.” The site never saw you | [407 Proxy Authentication Required](https://scrapenews.com/errors/407-proxy-authentication-required.md) |

## Fix it

1. **Read the body.** A vendor’s JSON or text names the reason (`AUTH001`, `Invalid API key`, `Unauthorized: Invalid token`). An HTML login page means the target site sent it.
2. **Check the key your code really sends.** Print its length and first 4 characters, but never the entire key. Empty or `None` means the environment variable did not load.
3. **Copy the key once more** from the vendor’s dashboard. If someone regenerated it, the old one is dead.
4. **Send it the way your vendor wants** (table in Dev details). For a Bearer header, write it exactly: `Authorization: Bearer <key>`, capital B, one space.
5. **Token expired?** Get a new one at the login or token endpoint, then retry once. RFC 6750 allows exactly that.
6. **Behind a site login?** Log in again and take the fresh cookies, then check the session cookie’s `Expires` or `Max-Age` so you know when to refresh it next time.
7. **Using an IP allowlist (Scrapfly)?** Add the IP the error message names to the project settings or clear the field.
8. **Don’t retry in a loop.** Firecrawl marks its 401 as not retryable. The same key will get the same answer.

Using a vendor as a proxy (`host:port` plus a username and password)? A bad login there comes back as 407, not 401. See [407 Proxy Authentication Required](https://scrapenews.com/errors/407-proxy-authentication-required.md).

Why the body comes first: vendors put the exact reason there, and RFC 9110 tells clients to show it. Guessing costs more time than simply reading it.

Treat your key as a password:

- Put it in an environment variable or a secrets manager, and never in git (ZenRows).
- Keep it out of URLs when the vendor allows a header. RFC 6750 says bearer tokens should not go in page URLs, because browser history and server logs may keep them.
- Asking for help? Replace the key with `KEY` before you share a request URL anywhere.
- Leaked it? Make a fresh key in the dashboard. That kills the old one, which is cause 3 by design.

One trap for AI agent templates: Firecrawl’s `/v1/scrape` and `/v1/search` work without a key, with limits. But only if you leave the `Authorization` header out, because a header with a blank token gets 401.

Paste this into your AI

```
My scraper gets this error: "<paste the exact error line>".
Explain in plain words what a 401 means.
First tell me how to see who sent it: my scraping API (my key) or the target site (its login).
Then list the likely causes in order, most likely first.
For each cause, give one quick test and one fix.
My setup: <language + library>, <scraping API or proxy vendor, or none>,
how I send the key (<query parameter / Authorization: Bearer / X-API-Key / cookie>),
the URL pattern I call: <URL, with the key replaced by KEY>.
Response headers and the first 20 lines of the body: <paste them>.
Never ask me to paste my real key, token or cookie.
```

## Dev details

**The challenge header.** A server that sends 401 MUST send a `WWW-Authenticate` header with at least one challenge, which names the login scheme it wants (RFC 9110). You answer with an `Authorization` header.

```http
HTTP/1.1 401 Unauthorized
Date: Tue, 02 Jul 2024 12:18:47 GMT
WWW-Authenticate: Bearer
```

With an expired OAuth token, RFC 6750 shows this example:

```http
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                  error="invalid_token",
                  error_description="The access token expired"
```

If you already sent a credential and get the same challenge back, RFC 9110 says the client should show the body to the user, since that body usually explains what went wrong.

**Where each vendor wants the credential:**

| vendor | how to send it | 401 body or code |
| --- | --- | --- |
| ZenRows Fetch | `apikey` query parameter | `AUTH001` missing · `AUTH002` malformed · `AUTH003` not found |
| ZenRows Batch | `X-API-Key` header only | `unauthenticated` |
| Firecrawl | `Authorization: Bearer fc-...` | `{"success": false, "error": "Unauthorized: Invalid token"}` |
| Bright Data Web Unlocker (Direct API) | `Authorization: Bearer <API key>` | plain text, see below |
| ScraperAPI | `api_key` query parameter | `Unauthorized request, please make sure your API key is valid.` |
| Scrapfly | `key` query parameter | JSON with `"http_code": 401`, `"message": "Invalid API key"` |

```bash
# ZenRows Fetch: key in the query string
curl "https://api.zenrows.com/v1/?apikey=YOUR_ZENROWS_API_KEY&url=https%3A%2F%2Fhttpbin.io%2Fanything"
```

**Bright Data Web Unlocker.** Key checks happen before the unlocker runs, so on `api.brightdata.com/request` you get a real outer 401 with a plain-text message body and no `x-brd-*` headers:

| body | cause |
| --- | --- |
| `Invalid token` | well-formed, but not a valid key (revoked, mistyped) |
| `Auth method is not supported` | not the Bearer scheme: bare key, `Token <key>`, lowercase `bearer`, extra spaces |
| `Credentials are invalid` | Basic auth instead of Bearer |
| `User authentication is required` | no `Authorization` header |

Once a request passes those checks, a missing `x-brd-error` header tells you the response came from the target site itself.

**Scrapfly** sends back a JSON error:

```json
{
    "status": "error",
    "http_code": 401,
    "reason": "Unauthorized",
    "error_id": "301e2d9e-b4f5-4289-85ea-e452143338df",
    "message": "Invalid API key"
}
```

**What your HTTP client prints.**

| library | message |
| --- | --- |
| Python requests (`raise_for_status()`) | `401 Client Error: Unauthorized for url: <url>` |
| Axios | `Request failed with status code 401` |

**Python requests and a Bearer key from an environment variable:**

```python
import os
import requests

key = os.environ.get("FIRECRAWL_API_KEY")
print(len(key or ""), (key or "")[:4])  # check it loaded, never print it all

r = requests.post(
    "https://api.firecrawl.dev/v2/scrape",
    headers={"Authorization": f"Bearer {key}"},
    json={"url": "https://example.com"},
)
if r.status_code == 401:
    print(r.text)  # the vendor's reason
r.raise_for_status()
```

**Basic auth is not a lock.** The Basic scheme sends `user:password` written in Base64 (RFC 7617). Base64 is a way of spelling bytes, which means anyone who sees the header can read it back. RFC 7617’s own example: user `test`, password `123£` becomes `dGVzdDoxMjPCow==`. The RFC calls Basic unsafe unless it runs inside TLS, so only use it over `https://`.

**Branch on the code, not the text.** Bright Data’s messages carry request-specific details, so it asks you to check its error code instead. The same goes for ZenRows’ `AUTH00x` codes and Firecrawl’s optional `code` field.

**Agents can read their way out.** ZenRows’ remote MCP server answers a headless agent that has no key with a 401. Its body names a signup endpoint in an `agent_signup` field, and one network can create 3 such agent accounts in 24 hours.

## Questions

### What is the difference between 401 and 403?

401 means the server has no valid login from you: send one, or a better one. 403 means it understood the request and still says no, even if your login is fine (MDN, RFC 9110).

### What is the difference between 401 and 407?

401 comes from the server you called and wants an Authorization header. 407 comes from a proxy in between and wants a Proxy-Authorization header (RFC 9110).

### Does a 401 from a scraping API mean I ran out of credits?

Usually not. ScraperAPI answers 403 when your monthly credits run out, ZenRows and Firecrawl answer 402. A 401 points at the key itself: missing, mistyped or revoked.

## Related

- [Python web scraping](https://scrapenews.com/guides/python-requests-beautifulsoup.md)  (Guide)
- [Is web scraping legal? EU vs US rules, and ethical proxies (2026)](https://scrapenews.com/guides/is-web-scraping-legal.md)  (Guide)
- [Scraper and unblocker APIs](https://scrapenews.com/compare/scraper-apis.md)  (Compare)
- [403 Forbidden when scraping](https://scrapenews.com/errors/403-forbidden.md)  (Error)
- [429 Too Many Requests](https://scrapenews.com/errors/429-too-many-requests.md)  (Error)
- [502 Bad Gateway and 504 Gateway Timeout](https://scrapenews.com/errors/502-504-bad-gateway-timeout.md)  (Error)

## Tools that get past it

| Tool | Price |
| --- | --- |
| [Bright Data Web Unlocker](https://scrapenews.com/compare/bright-data.md): Unblocking API from Bright Data: you send a URL, it handles proxies, retries and CAPTCHAs. Billed per 1,000 requests. | $1.50/1k req |
| [Firecrawl](https://scrapenews.com/compare/firecrawl.md): Turns websites into Markdown or structured data for AI: scrape, crawl, search, plus Alexandria data tools agents can run. Open source (AGPL) plus a hosted API. | $3.80/1k req |
| [Requests](https://scrapenews.com/compare/requests.md): The classic simple HTTP library for Python. | Free |
| [ScraperAPI](https://scrapenews.com/compare/scraperapi.md): Scraping API that rotates proxies and can render JavaScript. Monthly credit plans; harder pages cost more credits. | $0.49/1k req |
| [Scrapfly](https://scrapenews.com/compare/scrapfly.md): Scraping API with anti-bot bypass, browser rendering and screenshots, using one credit pool across products. | $0.15/1k req |
| [ZenRows](https://scrapenews.com/compare/zenrows.md): Scraping API with JavaScript rendering and premium proxies, priced in credits per page. Free plan with 5,000 credits a month. | $0.42/1k req |

## Sources

1. [RFC 9110 §15.5.2: 401 Unauthorized](https://www.rfc-editor.org/rfc/rfc9110#status.401) rfc-editor.org
2. [RFC 9110 §11.3: Challenge and Response](https://www.rfc-editor.org/rfc/rfc9110#section-11.3) rfc-editor.org
3. [RFC 9110 §15.5.4: 403 Forbidden](https://www.rfc-editor.org/rfc/rfc9110#status.403) rfc-editor.org
4. [MDN: 401 Unauthorized](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/401) developer.mozilla.org
5. [RFC 6750: OAuth 2.0 Bearer Token Usage (invalid_token)](https://www.rfc-editor.org/rfc/rfc6750) rfc-editor.org
6. [MDN: Using HTTP cookies (cookie lifetime)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies) developer.mozilla.org
7. [RFC 7617: The 'Basic' HTTP Authentication Scheme](https://www.rfc-editor.org/rfc/rfc7617) rfc-editor.org
8. [ZenRows Docs: API Authentication](https://docs.zenrows.com/authentication) docs.zenrows.com
9. [ZenRows Docs: API Error Codes (AUTH001–AUTH003)](https://docs.zenrows.com/api-error-codes) docs.zenrows.com
10. [ScraperAPI Docs: API Status Codes](https://docs.scraperapi.com/responses-and-formats/api-status-codes) docs.scraperapi.com
11. [Firecrawl Docs: Errors](https://docs.firecrawl.dev/api-reference/errors) docs.firecrawl.dev
12. [Firecrawl Docs: API Introduction (authentication)](https://docs.firecrawl.dev/api-reference/introduction) docs.firecrawl.dev
13. [Bright Data Docs: Web Unlocker API error codes](https://docs.brightdata.com/products/web-unlocker/error-codes) docs.brightdata.com
14. [Scrapfly Docs: Web Scraping API Errors](https://scrapfly.io/docs/scrape-api/errors) scrapfly.io
15. [Scrapfly Docs: Getting Started (key parameter)](https://scrapfly.io/docs/scrape-api/getting-started) scrapfly.io
16. [ScraperAPI Docs: Using the API Endpoint (api_key)](https://docs.scraperapi.com/synchronous-apis/using-the-api-endpoint) docs.scraperapi.com
17. [Requests docs: Custom Headers (Authorization precedence)](https://requests.readthedocs.io/en/latest/user/quickstart/#custom-headers) requests.readthedocs.io
18. [psf/requests source: models.py (raise_for_status message)](https://github.com/psf/requests/blob/v2.32.3/src/requests/models.py) github.com
19. [Axios source: settle.js error message](https://github.com/axios/axios/blob/v1.x/lib/core/settle.js) github.com

## Up

- [Home](https://scrapenews.com/index.md)
- [Errors & CAPTCHAs](https://scrapenews.com/errors.md)
