Working with Authorization Headers
1. Using Authorization Header Format
| Syntax | RFC 7235 |
|---|---|
| General | Authorization: <scheme> <credentials> |
| Bearer | Authorization: Bearer eyJ... |
| Basic | Authorization: Basic base64(user:pass) |
| Digest | Authorization: Digest username="..." |
| DPoP | Authorization: DPoP <token> + DPoP: <proof> |
2. Implementing Bearer Token Scheme
| Spec | RFC 6750 |
|---|---|
| Transport | HTTPS only |
| Error response | WWW-Authenticate: Bearer error="invalid_token" |
| Alternative locations | Form body (access_token=), URI (discouraged) |
3. Using Basic Authentication Scheme
| Aspect | Detail |
|---|---|
| Format | base64(username:password) |
| Encoding | UTF-8 (RFC 7617) |
| Security | Reversible — TLS mandatory |
| Use | Admin APIs, M2M, legacy |
| Realm | WWW-Authenticate: Basic realm="API" |
4. Implementing Digest Authentication Scheme
| Aspect | RFC 7616 |
|---|---|
| Mechanism | Challenge-response with MD5/SHA-256 |
| Pro | Password not in clear |
| Con | Server stores HA1 — equivalent to password |
| Status | Largely replaced by token/Bearer |
5. Using API Key in Headers
| Pattern | Example |
|---|---|
| Custom header | X-API-Key: abc123 |
| Authorization scheme | Authorization: ApiKey abc123 |
| Prefix | Include identifier: pk_live_... |
| Storage | Hash in DB (SHA-256), prefix searchable |
6. Implementing Custom Authentication Schemes
Example: HMAC signature scheme
Authorization: HMAC-SHA256 KeyId=AK123,Signature=base64(hmac)
X-Timestamp: 2026-05-18T12:00:00Z
# String-to-sign:
METHOD + "\n" + PATH + "\n" + QUERY + "\n" + TIMESTAMP + "\n" + sha256(body)
7. Handling Missing Authorization Headers
| Case | Response |
|---|---|
| Missing header | 401 + WWW-Authenticate: Bearer |
| Wrong scheme | 401 + correct scheme list |
| Public endpoint | Skip auth, log anonymous |
8. Parsing Authorization Header Values
Example: Defensive parsing
function parseAuth(h) {
if (!h) return null;
const m = /^(\w+)\s+(.+)$/i.exec(h.trim());
if (!m) return null;
return { scheme: m[1].toLowerCase(), credentials: m[2] };
}
9. Implementing Multiple Authentication Methods
| Order | Detail |
|---|---|
| Priority | Bearer > mTLS > API Key > Basic |
| Try chain | First successful wins |
| Response | If all fail, return list of supported schemes |
10. Setting Authorization Header in HTTP Clients
| Client | Example |
|---|---|
| fetch | headers: { Authorization: "Bearer " + t } |
| axios | axios.defaults.headers.common.Authorization = ... |
| curl | curl -H "Authorization: Bearer $T" |
| OkHttp | Interceptor adds header automatically |