Category:Scraping ErrorsView as Markdown

401 Unauthorized: Why Your Credentials Didn't Work

Clock23 Mins Read
calendarCreated Date: November 30, 2026
calendarUpdated Date: November 30, 2026
author

Software Engineer

githublinkedin

A 401 Unauthorized means the server didn't get valid credentials with your request. The API key, token or password was missing, wrong, expired, or sent somewhere the server doesn't look. The last one catches people with correct credentials, and its most common form is a token sent without its scheme:

import requests

url = "https://httpbin.org/bearer"
token = "my-token"

r = requests.get(url, headers={"Authorization": token}, timeout=30)  # token without its scheme
print(r.status_code, r.headers.get("WWW-Authenticate"))

r = requests.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=30)
print(r.status_code, r.json())
401 Bearer
200 {'authenticated': True, 'token': 'my-token'}

The 401's WWW-Authenticate header names the scheme the server expects, here Bearer. Send the credential that header asks for, in the form the API's docs show, and the 401 goes away. Sending the same request again never does.

In a browser, a 401 means the page wants a login you didn't give, or rejected the one your browser saved. Check the URL, sign in again, and clear that site's cookies if it keeps happening; the steps for users and site owners have their own section.

Missing, Wrong, Expired or Lost: Read the Challenge First

RFC 9110 requires a server that sends a 401 to include a WWW-Authenticate header with at least one challenge. If your request already carried credentials, the 401 means the server refused those, and you may try again with new ones. MDN's reference page puts it the same way. Despite the name, a 401 is about authentication (who you are), not permission.

A real challenge looks like this. Docker Hub's registry API answers an anonymous request for a public image's tags with a 401 that spells out how to get in:

curl -s -i https://registry-1.docker.io/v2/library/alpine/tags/list | grep -i -E "^HTTP|^www-authenticate"
HTTP/1.1 401 Unauthorized
www-authenticate: Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:library/alpine:pull"

The scheme is Bearer, and the parameters say where to get a token and for what scope. The challenge, plus the body, usually tells you which of these you're dealing with:

Cause What you'll usually see
No credentials sent A bare challenge, such as WWW-Authenticate: Bearer realm="api"
Wrong username, password or API key The same challenge, or a JSON message like "Bad credentials"
Expired or revoked token error="invalid_token" in the challenge
Right credential, wrong place A key in the query string when the API reads a header, or a token without the word Bearer
Credentials dropped on the way A redirect to another host, or a client that strips the header

Send Docker's registry a token it didn't issue, and the challenge gains an error parameter:

import requests

URL = "https://registry-1.docker.io/v2/library/alpine/tags/list"

r = requests.get(URL, headers={"Authorization": "Bearer not-a-real-token"}, timeout=30)
print(r.status_code, r.reason)
print(r.headers["WWW-Authenticate"])
401 Unauthorized
Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:library/alpine:pull",error="invalid_token"

RFC 6750, the Bearer token spec, defines three error codes and the status that goes with each:

error= value Status What it means Fix
(none) 401 You sent no token at all Send one
invalid_request 400 The request is malformed, such as two tokens at once Send one token, one way
invalid_token 401 Expired, revoked or malformed token Get a new token
insufficient_scope 403 Valid token without the needed permission Request a token with that scope

APIs That Skip the Header

Plenty of APIs ignore the spec here. GitHub's REST API sends a 401 with a JSON message and no WWW-Authenticate at all:

import requests

for headers in [{}, {"Authorization": "Bearer not-a-real-token"}]:
    r = requests.get("https://api.github.com/user", headers=headers, timeout=30)
    print(r.status_code, r.json()["message"], "| WWW-Authenticate:", r.headers.get("WWW-Authenticate"))
401 Requires authentication | WWW-Authenticate: None
401 Bad credentials | WWW-Authenticate: None

"Requires authentication" means nothing was sent; "Bad credentials" means the token was wrong. Without the header, that message is all you get, so log the body of every 401.

Following a Challenge to Get a Token

When the header is there, you can act on it. Docker's registry hands out anonymous pull tokens for public images, so the challenge alone is enough to finish the request:

import re

import requests

URL = "https://registry-1.docker.io/v2/library/alpine/tags/list"

r = requests.get(URL, timeout=30)
challenge = r.headers["WWW-Authenticate"]
print(r.status_code, challenge)

# Bearer realm="...",service="...",scope="..." -> {"realm": ..., "service": ..., "scope": ...}
params = dict(re.findall(r'(\w+)="([^"]*)"', challenge))
token = requests.get(params.pop("realm"), params=params, timeout=30).json()["token"]

r = requests.get(URL, headers={"Authorization": f"Bearer {token}"}, timeout=30)
print(r.status_code, r.json()["tags"][:4])
401 Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:library/alpine:pull"
200 ['2.6', '2.7', '20190228', '20190408']

The regex is enough for a single challenge like this one. A header can carry several challenges separated by commas, and a full parser has to handle that.

401 vs 403 vs 407: What's the Difference?

A 401 means the server doesn't know who you are. A 403 means it knows, and the answer is still no. A 407 comes from a proxy between you and the server, which needs its own login before it forwards anything. Each one carries a different header and needs a different fix.

Code Sent by Header it carries What it means Does sending credentials help?
401 Unauthorized The server WWW-Authenticate No valid credentials Yes, the right ones
403 Forbidden The server Sometimes WWW-Authenticate with insufficient_scope Credentials are fine but not enough, or access is refused outright Only if another account has access (403 guide)
407 Proxy Authentication Required Your proxy Proxy-Authenticate The proxy wants its own login Yes, proxy credentials (407 guide)
429 Too Many Requests The server Retry-After Too many requests No, slowing down does (429 guide)

Diagram of who sends each code: a 407 from the proxy with Proxy-Authenticate, a 401 from the server when no valid credential arrived, a 403 when it knows you and refuses

RFC 9110 defines 403 as a refusal the client SHOULD NOT repeat with the same credentials, and 407 as "similar to 401" but for a proxy. Real APIs blur the split. NASA's API gateway answers a request with no API key with a 403, not a 401:

curl -s -w "\n%{http_code}\n" https://api.nasa.gov/planetary/apod
{
  "error": {
    "code": "API_KEY_MISSING",
    "message": "No api_key was supplied. Get one at https://api.nasa.gov:443"
  }
}
403

So read the body as well as the code. Some servers stretch the codes further still and answer banned clients with a 418 I'm a teapot.

If you scrape public pages rather than call APIs, Scrape.do's web scraping API handles the proxies and headers for you. Its header options can also forward your own Authorization header to an API you hold a key for, shown in the Scrape.do section, and you can get a free API token to try it.

A Local Server With Every Kind of 401

Public APIs show a few cases each. This server shows all of them, including a token that expires while you watch, which is hard to catch in the wild. It uses Python's standard library only: Basic auth on /basic, five-second Bearer tokens on /api/me, an API key header on /api/key, a redirect to another host name on /old-basic, and a proxy mode that answers 407.

import base64
import json
import secrets
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit

USERS = {"demo": "s3cret"}             # Basic auth on /basic
API_KEYS = {"key-123"}                 # X-API-Key header on /api/key
CLIENTS = {"my-client": "my-secret"}   # client credentials for POST /token
TOKEN_TTL = 5                          # seconds; short so you can watch a token expire
TOKENS = {}                            # access token -> expiry time
PROXY_LOGIN = "proxyuser:proxypass"    # Proxy-Authorization when used as a proxy


class Handler(BaseHTTPRequestHandler):
    server_version, sys_version = "auth-demo/1.0", ""

    def do_GET(self):
        url = urlsplit(self.path)
        if url.scheme:  # an absolute URL means the client is using us as a proxy
            return self.proxy()
        routes = {"/basic": self.basic, "/api/me": self.bearer, "/api/admin": self.bearer,
                  "/api/key": self.api_key, "/old-basic": self.moved}
        routes.get(url.path, self.not_found)(url)

    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        form = parse_qs(self.rfile.read(length).decode())
        client_id = form.get("client_id", [""])[0]
        if urlsplit(self.path).path != "/token" or CLIENTS.get(client_id) != form.get("client_secret", [""])[0]:
            return self.reply(401, {"error": "invalid_client"}, {"WWW-Authenticate": 'Basic realm="token"'})
        token = secrets.token_urlsafe(16)
        TOKENS[token] = time.time() + TOKEN_TTL
        self.reply(200, {"access_token": token, "token_type": "Bearer", "expires_in": TOKEN_TTL})

    def basic(self, url):
        auth = self.headers.get("Authorization", "")
        if auth.startswith("Basic "):
            user, _, password = base64.b64decode(auth[6:]).decode().partition(":")
            if USERS.get(user) == password:
                return self.reply(200, {"user": user})
        self.reply(401, {"error": "bad or missing credentials"},
                   {"WWW-Authenticate": 'Basic realm="demo", charset="UTF-8"'})

    def bearer(self, url):
        auth = self.headers.get("Authorization", "")
        if not auth.startswith("Bearer "):  # no token: a bare challenge (RFC 6750, section 3.1)
            return self.reply(401, {"error": "missing token"}, {"WWW-Authenticate": 'Bearer realm="demo"'})
        expiry = TOKENS.get(auth[7:])
        if expiry is None or expiry < time.time():
            why = "The access token expired" if expiry else "The access token is invalid"
            challenge = f'Bearer realm="demo", error="invalid_token", error_description="{why}"'
            return self.reply(401, {"error": "invalid_token"}, {"WWW-Authenticate": challenge})
        if url.path == "/api/admin":  # valid token, but it only carries the "read" scope
            challenge = 'Bearer realm="demo", error="insufficient_scope", scope="admin"'
            return self.reply(403, {"error": "insufficient_scope"}, {"WWW-Authenticate": challenge})
        self.reply(200, {"user": "my-client", "scope": "read"})

    def api_key(self, url):
        if self.headers.get("X-API-Key") in API_KEYS:
            return self.reply(200, {"ok": True})
        if "api_key" in parse_qs(url.query):  # right key, wrong place
            return self.reply(401, {"error": "send the key in the X-API-Key header"})
        self.reply(401, {"error": "missing API key"})  # like many real APIs: no WWW-Authenticate

    def moved(self, url):  # redirects to another host name for the same server
        self.reply(301, {}, {"Location": "http://localhost:8401/basic"})

    def proxy(self):
        expected = "Basic " + base64.b64encode(PROXY_LOGIN.encode()).decode()
        if self.headers.get("Proxy-Authorization") != expected:
            return self.reply(407, {"error": "proxy login required"},
                              {"Proxy-Authenticate": 'Basic realm="demo proxy"'})
        self.reply(200, {"proxied": self.path})  # a real proxy would fetch the URL here

    def not_found(self, url):
        self.reply(404, {"error": "not found"})

    def reply(self, status, body, headers=None):
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        for name, value in (headers or {}).items():
            self.send_header(name, value)
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):  # keep the terminal quiet
        pass


ThreadingHTTPServer(("127.0.0.1", 8401), Handler).serve_forever()

Save it as server_401.py, start it with python server_401.py, and leave it running. Then send it the six requests that fail most often in real code:

import requests

BASE = "http://127.0.0.1:8401"
cases = [
    ("no credentials", "/basic", {}),
    ("wrong password", "/basic", {"auth": ("demo", "wrong")}),
    ("no token", "/api/me", {}),
    ("invalid token", "/api/me", {"headers": {"Authorization": "Bearer abc123"}}),
    ("key in query", "/api/key?api_key=key-123", {}),
    ("no key", "/api/key", {}),
]

for label, path, kwargs in cases:
    r = requests.get(BASE + path, timeout=10, **kwargs)
    print(f"{label:15} {r.status_code}  {r.json()['error']:38} {r.headers.get('WWW-Authenticate', '-')}")
no credentials  401  bad or missing credentials             Basic realm="demo", charset="UTF-8"
wrong password  401  bad or missing credentials             Basic realm="demo", charset="UTF-8"
no token        401  missing token                          Bearer realm="demo"
invalid token   401  invalid_token                          Bearer realm="demo", error="invalid_token", error_description="The access token is invalid"
key in query    401  send the key in the X-API-Key header   -
no key          401  missing API key                        -

The first two look identical on purpose. A server that said whether the username or the password was wrong would be helping anyone who guesses logins. The same server also produces the two neighbouring codes, so you can see all three side by side:

import requests

BASE = "http://127.0.0.1:8401"
form = {"client_id": "my-client", "client_secret": "my-secret"}
token = requests.post(f"{BASE}/token", data=form, timeout=10).json()["access_token"]

r = requests.get(f"{BASE}/api/me", timeout=10)  # no token at all
print(r.status_code, r.reason, "|", r.headers["WWW-Authenticate"])

r = requests.get(f"{BASE}/api/admin", headers={"Authorization": f"Bearer {token}"}, timeout=10)  # wrong scope
print(r.status_code, r.reason, "|", r.headers["WWW-Authenticate"])

r = requests.get("http://example.com/", proxies={"http": BASE}, timeout=10)  # a proxy, no proxy login
print(r.status_code, r.reason, "|", r.headers["Proxy-Authenticate"])
401 Unauthorized | Bearer realm="demo"
403 Forbidden | Bearer realm="demo", error="insufficient_scope", scope="admin"
407 Proxy Authentication Required | Basic realm="demo proxy"

Why Do I Get a 401 When My Credentials Are Correct?

Because they never reach the server in a form it reads. Three of the local server's cases fail that way, and each fix is one change in requests: a (user, password) tuple for Basic auth, the API key in the header the API documents, and the word Bearer in front of the token.

import requests

BASE = "http://127.0.0.1:8401"

# Basic auth: pass a (user, password) tuple and requests builds the header
r = requests.get(f"{BASE}/basic", auth=("demo", "s3cret"), timeout=10)
print("basic      ", r.status_code, r.json())

# API key: in the header the API documents, not in the query string
r = requests.get(f"{BASE}/api/key", headers={"X-API-Key": "key-123"}, timeout=10)
print("api key    ", r.status_code, r.json())

# Bearer: the scheme name, a space, then the token
form = {"client_id": "my-client", "client_secret": "my-secret"}
token = requests.post(f"{BASE}/token", data=form, timeout=10).json()["access_token"]
for value in [token, f"Bearer {token}"]:
    r = requests.get(f"{BASE}/api/me", headers={"Authorization": value}, timeout=10)
    print("with Bearer" if value.startswith("Bearer") else "token only ", r.status_code, r.json())
basic       200 {'user': 'demo'}
api key     200 {'ok': True}
token only  401 {'error': 'missing token'}
with Bearer 200 {'user': 'my-client', 'scope': 'read'}

To the server, a valid token without Bearer in front is no token at all. Some APIs use another prefix, such as token or Bot, so copy the format from the API's docs rather than from memory. Two more causes to rule out: a token issued for a different environment, and a proxy or gateway that strips the header. When nothing obvious is wrong, print the request your client actually sent.

The Redirect That Drops Your Credentials

A requests.Session sends session.auth with every request, but requests removes the Authorization header when a redirect leads to a different host. That's a safety feature, and it produces a 401 that looks impossible, since you did send the password:

import requests

session = requests.Session()
session.auth = ("demo", "s3cret")  # sent on every request this session makes

r = session.get("http://127.0.0.1:8401/old-basic", timeout=10)
print([h.status_code for h in r.history], "->", r.status_code, r.url)

r = session.get("http://127.0.0.1:8401/basic", timeout=10)  # call the final URL directly
print(r.status_code, r.json())
[301] -> 401 http://localhost:8401/basic
200 {'user': 'demo'}

127.0.0.1 and localhost are the same machine but different host names, so requests dropped the header at the redirect. Check r.history whenever a 401 makes no sense, and call the final URL directly. The same rule explains 401s from APIs that redirect example.com to api.example.com or www.example.com.

Expired Tokens: Refresh Once, Then Stop

A 401 with error="invalid_token" in the middle of a job usually means the token outlived its lifetime. Get a new token and retry that one request, once. If the fresh token also gets a 401, the problem is the credentials behind it, and a loop would only hide that.

Tokens from OAuth client-credentials flows usually live minutes to hours, and a long crawl or sync job outlives them. The local server's tokens last five seconds, which makes the refresh easy to watch:

import time

import requests

BASE = "http://127.0.0.1:8401"


class TokenSession(requests.Session):
    """A session that gets a token, and gets a new one once when the API says it expired."""

    def __init__(self, token_url, client_id, client_secret):
        super().__init__()
        self.token_url = token_url
        self.form = {"client_id": client_id, "client_secret": client_secret}
        self.refresh()

    def refresh(self):
        r = super().request("POST", self.token_url, data=self.form, timeout=10)
        r.raise_for_status()
        self.headers["Authorization"] = "Bearer " + r.json()["access_token"]
        print("  got a new token")

    def request(self, method, url, **kwargs):
        r = super().request(method, url, **kwargs)
        if r.status_code == 401 and 'error="invalid_token"' in r.headers.get("WWW-Authenticate", ""):
            self.refresh()
            r = super().request(method, url, **kwargs)  # one retry with the new token, never a loop
        return r


api = TokenSession(f"{BASE}/token", "my-client", "my-secret")
print(api.get(f"{BASE}/api/me", timeout=10).status_code)
time.sleep(6)  # the demo server's tokens live 5 seconds
print(api.get(f"{BASE}/api/me", timeout=10).status_code)
  got a new token
200
  got a new token
200

The second call hit an expired token, got a 401, refreshed and succeeded, and the caller only saw the 200. If the API sends no WWW-Authenticate header, look for its own expiry message in the body instead, or refresh a little before the expires_in time the token endpoint gave you.

The Same Refresh in httpx

httpx has a hook made for this. Subclass httpx.Auth, and its auth_flow can fetch a token, send the request, and refresh once when the response is a 401. Basic auth takes the same (user, password) tuple as requests.

import time

import httpx

BASE = "http://127.0.0.1:8401"


class ClientCredentials(httpx.Auth):
    """Adds a Bearer token, and gets a new one when the server answers 401 invalid_token."""

    requires_response_body = True

    def __init__(self, token_url, client_id, client_secret):
        self.token_url = token_url
        self.form = {"client_id": client_id, "client_secret": client_secret}
        self.token = None

    def auth_flow(self, request):
        if self.token is None:
            self.token = yield from self.fetch_token()
        request.headers["Authorization"] = f"Bearer {self.token}"
        response = yield request
        if response.status_code == 401 and "invalid_token" in response.headers.get("WWW-Authenticate", ""):
            self.token = yield from self.fetch_token()
            request.headers["Authorization"] = f"Bearer {self.token}"
            yield request

    def fetch_token(self):
        response = yield httpx.Request("POST", self.token_url, data=self.form)
        print("  token request:", response.status_code)
        return response.json()["access_token"]


print(httpx.get(f"{BASE}/basic", auth=("demo", "s3cret")).json())  # Basic auth: a tuple, as in requests

with httpx.Client(auth=ClientCredentials(f"{BASE}/token", "my-client", "my-secret")) as client:
    print(client.get(f"{BASE}/api/me").status_code)
    time.sleep(6)
    print(client.get(f"{BASE}/api/me").status_code)
{'user': 'demo'}
  token request: 200
200
  token request: 200
200

The token logic lives in the auth class, and every request made with that client gets it. Set requires_response_body = True whenever the flow reads a response body, as this one does with the token endpoint's JSON.

Where fetch, axios, curl and Scrapy Trip You Up

fetch Rejects Credentials in the URL

http://user:pass@host works in curl, but Node's fetch throws before it sends anything. Build the Authorization header yourself:

const base = "http://127.0.0.1:8401";

// fetch rejects credentials inside the URL before it sends anything
try {
  await fetch("http://demo:s3cret@127.0.0.1:8401/basic");
} catch (err) {
  console.log(err.name + ":", err.message);
}

// Build the Basic header yourself
const basic = "Basic " + Buffer.from("demo:s3cret").toString("base64");
let res = await fetch(`${base}/basic`, { headers: { Authorization: basic } });
console.log(res.status, await res.json());

// A Bearer token goes in the same header, after the word Bearer
res = await fetch(`${base}/api/me`, { headers: { Authorization: "Bearer expired-or-wrong" } });
console.log(res.status, res.headers.get("www-authenticate"));
TypeError: Request cannot be constructed from a URL that includes credentials: http://demo:s3cret@127.0.0.1:8401/basic
200 { user: 'demo' }
401 Bearer realm="demo", error="invalid_token", error_description="The access token is invalid"

Save it as auth.mjs so top-level await works. Note the third line: fetch doesn't throw on a 401, so check res.status or res.ok yourself.

axios Hides the Challenge in err.response

axios does throw on a 401, with a message that leaves out the useful part. Install it with npm install axios and save this as axios_401.cjs:

const axios = require("axios");

const base = "http://127.0.0.1:8401";

(async () => {
  try {
    await axios.get(`${base}/basic`, { auth: { username: "demo", password: "wrong" } });
  } catch (err) {
    console.log(err.message);
    console.log("challenge:", err.response.headers["www-authenticate"]);
  }

  // auth builds the Basic header; for a token, use headers: { Authorization: `Bearer ${token}` }
  const res = await axios.get(`${base}/basic`, { auth: { username: "demo", password: "s3cret" } });
  console.log(res.status, res.data);
})();
Request failed with status code 401
challenge: Basic realm="demo", charset="UTF-8"
200 { user: 'demo' }

"Request failed with status code 401" is all axios prints by default. Log err.response.headers and err.response.data before you change anything.

curl: -u, Bearer Tokens and Redirects

Start with the challenge. -i prints the response headers above the body:

curl -s -i http://127.0.0.1:8401/api/me
HTTP/1.0 401 Unauthorized
Server: auth-demo/1.0
Content-Type: application/json
Content-Length: 26
WWW-Authenticate: Bearer realm="demo"

{"error": "missing token"}

Then send the credential the challenge names. Without credentials, with -u, and with an API key header:

curl -s -w " %{http_code}\n" http://127.0.0.1:8401/basic
curl -s -w " %{http_code}\n" -u demo:s3cret http://127.0.0.1:8401/basic
curl -s -w " %{http_code}\n" -H "X-API-Key: key-123" http://127.0.0.1:8401/api/key
{"error": "bad or missing credentials"} 401
{"user": "demo"} 200
{"ok": true} 200

For a Bearer token, fetch the token and pass it in the header:

TOKEN=$(curl -s -d client_id=my-client -d client_secret=my-secret http://127.0.0.1:8401/token | python -c "import sys, json; print(json.load(sys.stdin)['access_token'])")
curl -s -w " %{http_code}\n" -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8401/api/me
{"user": "my-client", "scope": "read"} 200

curl follows the same redirect rule as requests. With -L, it won't send your -u credentials to a different host unless you tell it to trust the redirect:

curl -s -L -w " %{http_code}\n" -u demo:s3cret http://127.0.0.1:8401/old-basic
curl -s -L --location-trusted -w " %{http_code}\n" -u demo:s3cret http://127.0.0.1:8401/old-basic
{"error": "bad or missing credentials"} 401
{"user": "demo"} 200

Use --location-trusted only when you know where the redirect goes, because it hands your password to the new host. If you copied the request with "Copy as cURL" in DevTools, our curl converter turns it into Python or Node code with the Authorization header in plain view.

Scrapy Drops the 401 Before parse Runs

The most direct fix works in every recent Scrapy version: build the header and attach it to the request that needs it.

import scrapy
from w3lib.http import basic_auth_header  # installed with Scrapy


class BasicAuthSpider(scrapy.Spider):
    name = "basic_auth"

    async def start(self):
        # the header rides on this request only, not on every site the spider reaches
        auth = basic_auth_header("demo", "s3cret")
        yield scrapy.Request("http://127.0.0.1:8401/basic", headers={"Authorization": auth})

    def parse(self, response):
        yield {"status": response.status, "user": response.json()["user"]}

Save it as basic_spider.py and run it:

scrapy runspider basic_spider.py -o basic.json
[
{"status": 200, "user": "demo"}
]

For a Bearer token, put f"Bearer {token}" in the same header instead of basic_auth.

With a wrong password, you don't get an error. Scrapy's HttpError middleware drops the 401 before parse runs and logs one line:

[scrapy.spidermiddlewares.httperror] INFO: Ignoring response <401 http://127.0.0.1:8401/basic>: HTTP status code is not handled or not allowed

Add handle_httpstatus_list = [401] to the spider if you want parse to see the 401 and stop the crawl yourself.

For Basic auth on every request to one site, HttpAuthMiddleware can add the header for you. The settings are HTTPAUTH_USER, HTTPAUTH_PASS and HTTPAUTH_DOMAIN (Scrapy's HttpAuthMiddleware docs), set in the spider's custom_settings (a fragment, not a full spider):

custom_settings = {
    "HTTPAUTH_USER": "demo",
    "HTTPAUTH_PASS": "s3cret",
    "HTTPAUTH_DOMAIN": "127.0.0.1:8401",
}

Older tutorials use the http_user, http_pass and http_auth_domain spider attributes. Scrapy now deprecates them, though older Scrapy versions read only those. The domain is required whenever a user or password is set, and credentials go only to that domain and its subdomains. Scrapy compares it with the URL's host and port: in our tests, "127.0.0.1" didn't match 127.0.0.1:8401, and the spider got a 401 with no warning. For a public API on the standard port, the host name alone ("api.example.com") is right.

401 or 407: When You Use a Proxy

A 407 comes from the proxy and needs proxy credentials in the proxy URL. A 401 comes from the target, which needs credentials of its own. Point requests at the local server as a proxy, first without a proxy login and then with one:

import requests

TARGET = "http://example.com/"

for proxy in ["http://127.0.0.1:8401", "http://proxyuser:proxypass@127.0.0.1:8401"]:
    r = requests.get(TARGET, proxies={"http": proxy}, timeout=10)
    print(r.status_code, r.reason, r.json())
407 Proxy Authentication Required {'error': 'proxy login required'}
200 OK {'proxied': 'http://example.com/'}

Proxy credentials go in the proxy URL; site credentials go in auth= or the Authorization header. Fixing one never fixes the other. On an HTTPS target, a proxy's 407 doesn't arrive as a response at all, because it happens while the tunnel is set up, and requests raises a ProxyError instead. Our 407 Proxy Authentication Required guide covers that case, and a browser shows the same failure as ERR_TUNNEL_CONNECTION_FAILED.

401 Errors From Scrape.do: Token or Target

Through Scrape.do, a 401 has two possible senders. Either your Scrape.do token is wrong, inactive or out of credits, and the JSON body comes from Scrape.do. Or the target returned the 401, and you'll see Scrape.do-Initial-Status-Code: 401 with the target's own body.

Here's what the API returns with no token and with a wrong one:

import urllib.parse

import requests

target = urllib.parse.quote("https://httpbin.co/anything")

for token in [None, "not-a-real-token"]:
    url = f"https://api.scrape.do/?url={target}" + (f"&token={token}" if token else "")
    r = requests.get(url, timeout=60)
    print(r.status_code, r.json()["Message"][0])
400 'Token' is required!
401 Scrape.do API Token is inactive or incorrect. Please check your token. If the issue persists, feel free to contact us via support@scrape.do

A missing token is a 400; a wrong one is a 401. The status codes page adds that a 401 also comes back when the account has no credits left or the subscription is suspended, and that repeated requests with an invalid token can get your IP throttled for a while. Check the token in your dashboard instead of retrying.

In proxy mode, the token is the proxy password, and the result depends on the target's scheme:

import requests

proxy = "http://not-a-real-token:@pm.scrape.do:8080"
proxies = {"http": proxy, "https": proxy}

r = requests.get("http://httpbin.co/anything", proxies=proxies, timeout=60)  # plain HTTP target
print(r.status_code, r.json()["Message"][0][:45])

try:
    requests.get("https://httpbin.co/anything", proxies=proxies, timeout=60)  # HTTPS target
except requests.exceptions.ProxyError as err:
    print("ProxyError:", err.args[0].reason.args[-1])
401 Scrape.do API Token is inactive or incorrect.
ProxyError: Tunnel connection failed: 407 Proxy Authentication Required

The same wrong token gives a 401 on an HTTP target and a 407 on an HTTPS one.

The other case is a target that requires credentials. By default, Scrape.do sends its own header set, so the Authorization header from your code doesn't reach the target. When you call an API you hold credentials for, add customHeaders=true and your headers go through as written:

import urllib.parse

import requests

token = "<your_token>"
target = urllib.parse.quote("https://httpbin.co/basic-auth/user/passwd")
api = f"https://api.scrape.do/?token={token}&url={target}"

r = requests.get(api, auth=("user", "passwd"), timeout=90)
print(r.status_code, r.headers.get("Scrape.do-Initial-Status-Code"), r.headers.get("WWW-Authenticate"))

# customHeaders=true forwards your own headers, Authorization included, to the target
r = requests.get(api + "&customHeaders=true", auth=("user", "passwd"), timeout=90)
print(r.status_code, r.json())
401 401 Basic realm="Fake Realm"
200 {'authenticated': True, 'user': 'user', 'authorized': True}

The first 401 is the target's: Scrape.do-Initial-Status-Code says so, and the target's WWW-Authenticate header comes back with it. If you need the target's exact status code on every response, add transparentResponse=true (response output docs). With customHeaders=true you replace Scrape.do's default headers, so send the full set the API needs (the custom headers docs cover the details).

To add a single header without replacing the defaults, use extraHeaders=true and send it as Sd-Authorization (extra headers docs):

import base64
import urllib.parse

import requests

token = "<your_token>"
target = urllib.parse.quote("https://httpbin.co/basic-auth/user/passwd")
basic = "Basic " + base64.b64encode(b"user:passwd").decode()

# extraHeaders=true keeps Scrape.do's headers and adds each Sd- header without the prefix
r = requests.get(
    f"https://api.scrape.do/?token={token}&url={target}&extraHeaders=true",
    headers={"Sd-Authorization": basic},
    timeout=90,
)
print(r.status_code, r.json())
200 {'authenticated': True, 'user': 'user', 'authorized': True}

In proxy mode, add customHeaders=true to the password to forward your own headers. Either way, your credentials pass through Scrape.do on the way, so do this only for APIs and accounts you're entitled to use.

Should Your Scraper Retry a 401?

No. The same request gets the same 401, so leave 401 out of your retry list. Refresh an expired token once if the credentials are yours, and stop otherwise.

Retries are for temporary failures: 429, 500, 502, 503 and 504. A retry setup for requests should list those and not 401, and your code should stop as soon as a 401 arrives:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])  # no 401 here
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))


def fetch(url):
    r = session.get(url, timeout=30)
    if r.status_code == 401:
        raise SystemExit(f"401 on {url}: the credentials are missing or wrong; retrying won't help")
    return r


print(fetch("https://httpbin.org/get").status_code)
fetch("https://httpbin.org/basic-auth/user/passwd")
200
401 on https://httpbin.org/basic-auth/user/passwd: the credentials are missing or wrong; retrying won't help

Like a 406 Not Acceptable, a 401 stays until the request changes. Hammering it can lock the account, get your IP throttled, and look like a password-guessing attack in the site's logs. Scrape.do throttles repeated invalid tokens for the same reason.

A 401 also marks a line for scraping. Public, logged-out pages are fair to collect; a page behind a login belongs to the people with accounts. Scrape.do is built for public pages, and this guide doesn't cover logging in to sites you have no account for. If a page you meant to scrape answers 401, it isn't public: skip it, and look for the same data on a public page or in an official API you can get a key for. Fixing a 401 is for APIs you hold credentials for and for your own services.

If You See 401 in a Browser or Own the Site

As a user, a 401 means the page wants a login. Work through these in order:

  1. Check the URL. A typo or an old bookmark can point at a protected folder instead of the public page.
  2. Sign in again. If the browser shows a username and password box, the site uses HTTP Basic auth, and a saved password that has since changed gets sent every time.
  3. Clear the site's cookies and cache. An expired session cookie can keep you stuck on a 401 after you log in.
  4. On sites with single sign-on, log out and back in. An expired token from the identity provider causes 401s across several apps at once.
  5. Ask the site owner if none of that works. Only they can see why the server refused you.

If you run the site or the API:

  • Send the challenge. A 401 without WWW-Authenticate breaks clients that follow the spec, and browsers won't show a login box without it.
  • Use 401 for "who are you?" and 403 for "I know you, and no". Clients refresh tokens on a 401 and give up on a 403, so mixing them up causes refresh loops or dead ends.
  • Say what went wrong in the body, without saying which half of a username and password pair failed.
  • Check the layers in front of the app. A password-protected folder in Apache or nginx, a CDN rule or a security plugin can each send 401s your application never sees.

Frequently Asked Questions

Why am I getting a 401 in Postman?

Postman sends whatever its Authorization tab produces, so start with the Postman Console, which shows the request as sent, headers included. If the Authorization header is missing, check the request's auth type: one set to inherit takes its auth from the collection or folder, and a token kept in an environment variable is only filled in when that environment is selected. If the header is there, read the response's WWW-Authenticate and body as you would in code.

What do "401 Authorization Required" and "Access is denied due to invalid credentials" mean?

Both are 401s, shown with a server's default error page. "401 Authorization Required" is the title of nginx's page, and the IIS version says "Access is denied due to invalid credentials". You'll usually see them on folders protected with HTTP Basic or Windows authentication. The fix is the same: send valid credentials.

Is a 401 my fault or the server's?

It's a client error, in the 4xx range, so the fix is on your side: the server works, and the request lacked valid credentials. Change what you send, not how often you send it. The exception is a site owner whose server sends 401s to visitors who should get in, which is a configuration problem on their end.