Lab-tested: Python 3.13.5 + raw-socket header cases · 2 Dec 2026 · Reproduced and fixed in our lab
Fix Box — Try This First (10 Seconds)
The correct shape is Authorization: Bearer <token> — scheme, exactly one space, token, nothing else. No quotes around the token, no trailing space, no colon after the scheme.
For Basic, encode user:password as UTF-8 before base64. If the header looks right but still fails, print its length and last four characters, never the value.
Start from the pillar 401 Unauthorized: Causes and How to Fix It or test with the 401 Checker.
Table of Contents
- The Only Shape That Works
- The Exact Responses (Verbatim from Our Lab)
- Mistake 1: Missing or Wrong Separator
- Mistake 2: Quoted or Padded Token
- Mistake 3: Case and Spacing Myths
- Mistake 4: Basic Encoding (UTF-8 vs Latin-1)
- Our Lab Reproduction
- The Fix, Step by Step
- What Did Not Work
- Prevention
- FAQ
- Sources and Date
- References
The Only Shape That Works
RFC 9110 defines the credentials syntax as an auth scheme, whitespace, and the credentials themselves. For Bearer, RFC 6750 narrows it to "Bearer" 1*SP b64token: the word Bearer, spaces, then the token characters.
There is no colon, no equals sign, and no quoting in the grammar.
Most header bugs come from string handling, not from the token. A config value with a trailing newline, a token wrapped in quotes by a JSON encoder, or a template that adds a colon "for readability" all produce a header the server cannot parse.
The server then reports a credential problem, and you debug the wrong layer.
The Exact Responses (Verbatim from Our Lab)
We sent eleven header variants at a Python 3.13.5 mock API on 2 Dec 2026, including raw-socket requests for tab characters. The pattern was consistent:
# Correct: Bearer + one space + token
HTTP/1.0 200 OK
# No space: "Bearer<token>"
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_request", error_description="Malformed Authorization header"
# Quoted token: Bearer "<token>"
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token", error_description="Malformed token value"
Note the two different errors. A broken shape earns invalid_request.
A parseable shape with a bad value earns invalid_token. That distinction tells you whether to fix your string building or your token.
Mistake 1: Missing or Wrong Separator
Bearer<token> with no space failed as invalid_request in our lab. So did Bearer: <token> with a colon, and a tab used as the separator between scheme and token. The grammar wants spaces (SP), and strict parsers enforce exactly that.
The colon variant is common because people copy the Header: value shape into the value itself. The tab variant appears when headers are built by joining fields with tabs from a spreadsheet or log file.
Both look fine to a human eye and fail on the wire.
Mistake 2: Quoted or Padded Token
Wrapping the token in double quotes — Bearer "<token>" — returned invalid_token in our lab. The quotes become part of the token value, so the server compares a different string.
This happens when a token passes through a JSON string that keeps its quotes, or a shell variable with literal quotes.
A trailing space after the token failed the same way. So did a double space between scheme and token against our strict lab parser.
Trailing whitespace usually rides in from environment variables, .env files, or copy-paste. Trim token values at load time, every time.
Mistake 3: Case and Spacing Myths
Two things people worry about that are actually fine. The scheme is case-insensitive: bearer <token> returned 200 in our lab, matching RFC 9110.
A tab after the header colon (Authorization:\tBearer ...) is legal optional whitespace and also returned 200.
The double-space case sits in between. RFC 6750's grammar allows one or more spaces, but our lab parser split on a single space and rejected it.
Real servers differ here. The safe habit is exactly one space, which every parser accepts.
Mistake 4: Basic Encoding (UTF-8 vs Latin-1)
Basic credentials are user:password encoded in base64. The question is which charset turns the password into bytes first. RFC 7617 defines the charset="UTF-8" parameter for exactly this reason.
Our lab used a password with a non-ASCII character (pässwörd-401, a lab fixture). UTF-8 encoding returned 200.
The same password encoded as Latin-1 returned 401 with a charset="UTF-8" challenge. If passwords contain non-ASCII characters and logins fail only for some users, encoding is the first suspect. See 401 Basic Auth Failures for the full Basic picture.
Our Lab Reproduction
Stack: Python 3.13.5 mock API plus raw-socket requests, tested 2 Dec 2026. Eleven cases: correct header, no space, colon separator, quoted token, lowercase scheme, double space, trailing space, tab separator, tab after colon, and Basic in UTF-8 vs Latin-1.
Results: 4 passed (correct, lowercase scheme, tab after colon, UTF-8 Basic), 7 returned 401 with the errors shown above.
Honest lab note: the mock parser is deliberately strict about the single-space split. Some production servers accept multiple spaces. Where the lab and the RFC grammar differ, the article says so; the portable rule is "one space, no decoration."
The Fix, Step by Step
- Build the header in one place with an f-string or equivalent:
f"Bearer {token}". Never concatenate by hand in multiple call sites. - Trim at load:
token = os.environ["TOKEN"].strip(). Reject empty values at startup. - Debug without leaking: log the header name, value length, and last four characters. Compare against a known-good curl request.
curl -si -H "Authorization: Bearer YOUR_TOKEN" https://your-api.example/endpoint
- For Basic, encode explicitly:
import base64
raw = f"{user}:{password}".encode("utf-8")
header = "Basic " + base64.b64encode(raw).decode("ascii")
- If curl works and the app fails, capture the app's exact header bytes (length first, then a masked diff). The bug is in string handling, not the token.
What Did Not Work
Adding quotes "to protect special characters" broke the token in our lab. Bearer tokens are already restricted to a safe character set; quotes only become part of the value.
Lowercasing the whole header value to "normalize" it would corrupt the token — only the scheme is case-insensitive. Tokens are case-sensitive opaque strings.
Sending the header twice (once by a framework, once manually) produces unpredictable results: servers may read the first, the last, or reject the request. Set it in exactly one layer.
Prevention
Centralize header construction in one auth helper and unit-test it against the malformed variants in this article. Lint config values for trailing whitespace.
Treat any invalid_request error as a client bug to fix in code, not a credential to rotate. For token lifetime issues, see Prevent 401: Token Refresh Done Right; for scheme-specific guides, 401 JWT/Bearer Token Errors and 401 Basic Auth Failures.
FAQ
**Does bearer lowercase work?** Yes. Auth schemes are case-insensitive per RFC 9110, and our lab accepted lowercase bearer. The token itself remains case-sensitive.
Is a double space after Bearer valid? The RFC 6750 grammar allows one or more spaces, but strict parsers (including our lab) reject it. Use exactly one space; it works everywhere.
Why does my token work in curl but not in my app? Your app is sending different bytes: quotes, trailing whitespace, a missing space, or an empty variable.
Log the value length and last four characters from the app and diff against the working curl header.
Can the password in Basic auth contain a colon? Yes.
The first colon separates user from password; later colons belong to the password. The user-id itself must not contain a colon.
Should I trim tokens from environment variables? Yes, always. A trailing newline from a secret file or .env entry silently changes the token value and produces invalid_token errors that look like revocation.
Sources and Date
Lab tests run 2 Dec 2026 on Python 3.13.5 (mock API + raw-socket cases, localhost). Captures are from that run with token values removed. References verified live on 2 Dec 2026.
References
- RFC 9110, HTTP Semantics, Section 11 (Authentication) and 15.5.2: https://www.rfc-editor.org/rfc/rfc9110.html
- RFC 6750, OAuth 2.0 Bearer Token Usage, Section 2.1 (Authorization header): https://www.rfc-editor.org/rfc/rfc6750.html
- RFC 7617, The 'Basic' HTTP Authentication Scheme (charset parameter): https://www.rfc-editor.org/rfc/rfc7617.html
- MDN Web Docs, Authorization header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
- MDN Web Docs, 401 Unauthorized: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/401





Leave a Reply