API Key phù hợp machine-to-machine, JWT cho stateless user auth, OAuth2 cho third-party authorization — mỗi pattern có trade-off riêng về security và complexity.
- API Key: chuỗi secret gửi trong header (
X-API-Key) hoặc query param — đơn giản, phù hợp server-to-server, machine-to-machine; không có expiry tự động; nếu lộ phải revoke thủ công. - JWT (JSON Web Token): self-contained token chứa claims (user ID, roles) được ký bằng secret/private key — stateless, không cần query DB mỗi request; có expiry; Access token (15 phút) + Refresh token (7-30 ngày) là pattern chuẩn; nhược điểm: không thể revoke trước expiry trừ khi dùng blocklist.
- OAuth2: authorization framework (không phải authentication) — cho phép third-party app access resource thay mặt user mà không cần share password; các flows: Authorization Code (web app), PKCE (mobile/SPA), Client Credentials (server-to-server), Device Flow (TV/CLI).
Thực tế: Internal API dùng JWT; Public API cho developers dùng API Key; Login với Google/GitHub dùng OAuth2 + OpenID Connect (OIDC) để lấy user identity.
API Key suits machine-to-machine auth, JWT enables stateless user auth, OAuth2 handles third-party authorization — each pattern has its own security and complexity trade-offs.
- API Key: a secret string sent in a header (
X-API-Key) or query parameter — simple, suitable for server-to-server or machine-to-machine communication; no automatic expiry; must be manually revoked if compromised. - JWT (JSON Web Token): a self-contained token carrying claims (user ID, roles) signed with a secret or private key — stateless, no DB lookup needed per request; has an expiry; the standard pattern is a short-lived access token (15 minutes) plus a refresh token (7–30 days); downside: cannot be revoked before expiry without a blocklist.
- OAuth2: an authorization framework (not an authentication protocol) — allows third-party apps to access resources on behalf of a user without sharing passwords; flows include Authorization Code (web apps), PKCE (mobile/SPA), Client Credentials (server-to-server), and Device Flow (TV/CLI).
In practice: internal APIs use JWT; public developer APIs use API Keys; login with Google/GitHub uses OAuth2 + OpenID Connect (OIDC) to obtain user identity.