Working with Authorization Headers

1. Using Authorization Header Format

SyntaxRFC 7235
GeneralAuthorization: <scheme> <credentials>
BearerAuthorization: Bearer eyJ...
BasicAuthorization: Basic base64(user:pass)
DigestAuthorization: Digest username="..."
DPoPAuthorization: DPoP <token> + DPoP: <proof>

2. Implementing Bearer Token Scheme

SpecRFC 6750
TransportHTTPS only
Error responseWWW-Authenticate: Bearer error="invalid_token"
Alternative locationsForm body (access_token=), URI (discouraged)

3. Using Basic Authentication Scheme

AspectDetail
Formatbase64(username:password)
EncodingUTF-8 (RFC 7617)
SecurityReversible — TLS mandatory
UseAdmin APIs, M2M, legacy
RealmWWW-Authenticate: Basic realm="API"

4. Implementing Digest Authentication Scheme

AspectRFC 7616
MechanismChallenge-response with MD5/SHA-256
ProPassword not in clear
ConServer stores HA1 — equivalent to password
StatusLargely replaced by token/Bearer

5. Using API Key in Headers

PatternExample
Custom headerX-API-Key: abc123
Authorization schemeAuthorization: ApiKey abc123
PrefixInclude identifier: pk_live_...
StorageHash 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

CaseResponse
Missing header401 + WWW-Authenticate: Bearer
Wrong scheme401 + correct scheme list
Public endpointSkip 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

OrderDetail
PriorityBearer > mTLS > API Key > Basic
Try chainFirst successful wins
ResponseIf all fail, return list of supported schemes

10. Setting Authorization Header in HTTP Clients

ClientExample
fetchheaders: { Authorization: "Bearer " + t }
axiosaxios.defaults.headers.common.Authorization = ...
curlcurl -H "Authorization: Bearer $T"
OkHttpInterceptor adds header automatically