API认证方式

认证方式对比

方式安全性无状态适用场景
API Key服务器间
JWTWeb/移动应用
OAuth2最高第三方授权访问
Basic Auth低(需HTTPS)简单内部工具
mTLS最高零信任微服务
Session Cookie高(配合HttpOnly)传统Web应用

JWT 结构

# JWT = base64(header).base64(payload).signature

# Header
{ "alg": "HS256", "typ": "JWT" }

# Payload (claims)
{
  "sub": "user_123",
  "iss": "api.example.com",
  "iat": 1704067200,
  "exp": 1704153600,    // expiry (24h later)
  "scope": "read:users write:profile"
}

# Usage in HTTP
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...

OAuth2 授权类型

# Authorization Code (web apps — most common)
1. Redirect user to /oauth/authorize?client_id=&response_type=code
2. User logs in, gets code
3. Exchange code for access_token (server-side)

# Client Credentials (server-to-server)
POST /oauth/token
grant_type=client_credentials
&client_id=xxx&client_secret=yyy
&scope=read:data

# PKCE (mobile/SPA — no secret exposed)
Use code_verifier + code_challenge for security

API Key最佳实践