Skip to content

Authentication Headers — Standard HTTP Headers for API Credential Transport

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Authentication Headers. We cover key concepts, practical examples, and best practices to help you master this topic.

HTTP authentication headers carry credentials between clients and servers, with standard formats defined by HTTP specifications and common conventions.

What You'll Learn

The standard HTTP authentication headers, their formats, when to use each, and implementation patterns for both request and response headers.

Why It Matters

Authentication headers follow established standards. Using the right headers in the correct format ensures compatibility with HTTP libraries, proxies, and frameworks. Incorrect headers cause authentication failures that are hard to debug.

Real-World Use

Every major API platform uses standard authentication headers. GitHub uses Authorization: Bearer, Stripe uses Authorization: Bearer, and Google uses both Authorization: Bearer for tokens and custom headers for API keys.

flowchart LR
    A["Client Request"] --> B["Headers"]
    B --> C["Authorization:\nBearer/Basic/Digest"]
    B --> D["X-API-Key:\nCustom API Key"]
    B --> E["Cookie:\nSession ID"]
    C --> F["Server Validation"]
    D --> F
    E --> F
    F --> G["200 OK or 401"]
    style A fill:#dbeafe,stroke:#2563eb
    style B fill:#fef3c7,stroke:#d97706
    style G fill:#dcfce7,stroke:#16a34a

Standard Request Headers

Header Format Example
Authorization <auth-scheme> <credentials> Authorization: Bearer eyJhbGci...
Authorization Basic <base64> Authorization: Basic YWRtaW46cGFzcw==
X-API-Key <key-value> X-API-Key: sk-live-abc123
Cookie <name>=<value> Cookie: session_id=abc123

Standard Response Headers

Header Purpose Example
WWW-Authenticate Challenge client for auth WWW-Authenticate: Bearer realm="api"
Set-Cookie Set session cookie Set-Cookie: session=abc; HttpOnly; Secure

Code Example: Parsing Different Auth Headers

from flask import Flask, request, jsonify
import base64

app = Flask(__name__)

def parse_auth_header():
    auth = request.headers.get("Authorization", "")

    if auth.startswith("Bearer "):
        token = auth[7:]
        return {"type": "bearer", "credentials": token}

    if auth.startswith("Basic "):
        decoded = base64.b64decode(auth[6:]).decode("utf-8")
        username, password = decoded.split(":", 1)
        return {"type": "basic", "username": username, "password": password}

    # Check custom header
    api_key = request.headers.get("X-API-Key")
    if api_key:
        return {"type": "api-key", "key": api_key}

    # Check cookie
    session_id = request.cookies.get("session_id")
    if session_id:
        return {"type": "session", "session_id": session_id}

    return None

@app.route("/api/auth-info")
def auth_info():
    auth_data = parse_auth_header()
    if not auth_data:
        return jsonify({"error": "No authentication found"}), 401

    return jsonify({
        "detected_auth_type": auth_data["type"],
        "headers_received": dict(request.headers)
    })

Code Example: Sending Challenge Response Header

from flask import make_response, jsonify

@app.route("/api/protected")
def protected():
    auth = request.headers.get("Authorization")
    if not auth:
        response = make_response(jsonify({
            "error": "Authentication required"
        }), 401)
        response.headers["WWW-Authenticate"] = (
            'Bearer realm="api", error="invalid_token", '
            'error_description="Access token required"'
        )
        return response
    # Process authenticated request...

Common Mistakes

1. Multiple Authorization Headers

HTTP does not support multiple headers with the same name. Send only one Authorization header. Use custom headers for additional auth data.

2. Case-Sensitivity Issues

Header names are case-insensitive (Authorization = authorization = AUTHORIZATION). Scheme names are convention (Bearer, not bearer).

3. Including Space in Credential Values

Base64-encoded credentials do not contain spaces. If your token has spaces, it is not valid.

4. Logging Authorization Headers

Auth headers contain credentials. Never log them. Sanitize or redact before logging.

5. Mixing Authentication Headers

Sending both Authorization: Basic and X-API-Key confuses servers. Pick one authentication method per request.

Practice Questions

  1. What is the difference between Authorization and WWW-Authenticate headers?
  2. Why should API keys be sent in custom headers rather than Authorization?
  3. What is the format of the Authorization header for Bearer tokens?
  4. How does the server indicate which auth scheme it supports?
  5. Can cookies and Authorization headers be used together?

Answers:

  1. Authorization is sent by the client to prove identity. WWW-Authenticate is sent by the server to challenge the client.
  2. Custom headers prevent conflicts with standard auth schemes. The server can look for X-API-Key without parsing the Authorization header.
  3. Authorization: Bearer <token-value> — the word Bearer followed by a space and the token.
  4. The server returns 401 with WWW-Authenticate header listing supported schemes (e.g., WWW-Authenticate: Basic realm="api", Bearer realm="api").
  5. Yes. A request can have both a Cookie (session) and Authorization (token) header. The server chooses which to use.

Challenge: Build a Flask middleware that detects and parses all common authentication headers, normalizes them to a standard user object, and returns proper challenge responses.

FAQ

What is the most common authentication header format?

Authorization: Bearer is the most common for modern APIs. It is standardized in RFC 6750.

Can I create custom authentication headers?

Yes. Prefix with X- (e.g., X-API-Key, X-Auth-Token). But prefer standard Authorization when possible.

Are HTTP headers case-sensitive?

Header names are case-insensitive. Header values may be case-sensitive depending on the scheme (Bearer tokens are typically case-sensitive).

What header should I use for API keys?

X-API-Key is the most common convention. Some APIs use Authorization: Bearer or a custom header.

How does a proxy affect authentication headers?

Proxies may modify or strip unknown headers. Use standard Authorization header for compatibility with enterprise proxies and firewalls.

Mini Project

Create an authentication header debugging tool that receives HTTP requests and prints the detected auth method, parsed credentials, and raw headers. Useful for testing API client implementations.

What's Next

Now learn about Authentication Middleware — reusable components that handle authentication logic across all API endpoints.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro