{
    "slug": "api_authentication_patterns",
    "term": "API Authentication Patterns",
    "category": "api_design",
    "difficulty": "intermediate",
    "short": "Bearer tokens (JWT) for user sessions, API keys for machine-to-machine, mTLS for highest-security internal services — matching authentication method to the use case.",
    "long": "API authentication options: Bearer token (Authorization: Bearer jwt) — stateless JWT, validate signature/expiry/issuer; use short expiry (15min) + refresh tokens. API key (X-API-Key header) — hash stored server-side, scope keys to minimum required permissions, rate-limit per key. Basic auth — only with HTTPS, legacy use only. OAuth 2.0 client credentials — for third-party apps accessing your API on their own behalf. mTLS (mutual TLS) — both client and server present certificates, no passwords, ideal for internal microservices. HMAC request signing (AWS Signature v4 style) — signs request body and headers, prevents replay attacks.",
    "aliases": [
        "Bearer token",
        "API key authentication",
        "mTLS",
        "HMAC signing",
        "JWT authentication"
    ],
    "tags": [
        "api-design",
        "security",
        "auth"
    ],
    "misconception": "JWT authentication is stateless and therefore cannot be revoked — JWTs cannot be revoked without maintaining a blocklist (which adds state); for revocability, use short-lived tokens (15min) where the window of exposure is acceptable, or use opaque tokens with server-side session lookup.",
    "why_it_matters": "API key authentication for public user-facing APIs means one leaked key compromises that entire user's access — JWT with short expiry + refresh tokens limits blast radius and enables revocation via refresh token blocklist.",
    "common_mistakes": [
        "Long-lived JWT tokens without revocation — a leaked token remains valid until expiry",
        "API keys in URL query parameters — logged by servers, CDNs, browser history, and proxies",
        "No token scoping — one token with full access means any leak is a full compromise",
        "JWT without signature validation — accepting unsigned tokens with alg:none"
    ],
    "when_to_use": [
        "API keys for server-to-server calls where the key can be stored securely in environment variables.",
        "OAuth 2.0 + PKCE for user-delegated access — never embed client secrets in mobile or SPA clients.",
        "JWT bearer tokens for stateless APIs where the token carries claims without server-side session lookup.",
        "mTLS for high-trust service-to-service communication in zero-trust network environments."
    ],
    "avoid_when": [
        "Using API keys in URLs — they appear in server logs, browser history, and referrer headers.",
        "Long-lived tokens with no expiry or rotation — a stolen token is valid forever.",
        "Storing API keys in client-side JavaScript — they are visible to anyone who views source.",
        "Using HTTP Basic Auth over plain HTTP — credentials are sent in every request, base64-encoded but not encrypted."
    ],
    "related": [
        "jwt_vulnerabilities",
        "api_key_management",
        "oauth2_flow",
        "openid_connect"
    ],
    "prerequisites": [
        "jwt_deep_dive",
        "oauth2_flow",
        "api_key_management"
    ],
    "refs": [
        "https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html"
    ],
    "bad_code": "// Long-lived JWT — leaked token valid for 1 year:\n$token = JWT::encode([\n    'sub' => $userId,\n    'exp' => time() + 31536000, // 1 year expiry!\n], $secretKey);\n// Leaked token: full access for up to 1 year\n\n// API key in URL — logged everywhere:\nGET /api/data?api_key=sk_live_abc123",
    "good_code": "// Short-lived access token + refresh token:\n$access  = JWT::encode(['sub'=>$userId,'exp'=>time()+900], $key);  // 15 min\n$refresh = JWT::encode(['sub'=>$userId,'exp'=>time()+2592000], $refreshKey); // 30 days\n// Leaked access token: valid at most 15 min\n// Refresh tokens: stored and rotatable\n\n// API key in header — not logged by default:\n// Authorization: Bearer $access\n// OR: X-API-Key: sk_live_abc123",
    "quick_fix": "API keys for server-to-server, JWT for stateless user sessions, OAuth2 for third-party delegated access — use the simplest pattern that meets your actual requirements",
    "severity": "high",
    "effort": "medium",
    "created": "2026-03-16",
    "updated": "2026-03-25",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/api_authentication_patterns",
        "html_url": "https://codeclaritylab.com/glossary/api_authentication_patterns",
        "json_url": "https://codeclaritylab.com/glossary/api_authentication_patterns.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[API Authentication Patterns](https://codeclaritylab.com/glossary/api_authentication_patterns) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/api_authentication_patterns"
            }
        }
    }
}