auth-ops
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth Operations
认证操作
Comprehensive authentication and authorization patterns for secure application development across languages and frameworks.
适用于跨语言和框架的安全应用开发的全面认证与授权模式。
Authentication Method Decision Tree
认证方法决策树
Use this tree to select the right authentication strategy for your use case.
What are you building?
│
├─ Traditional web application (server-rendered)?
│ └─ Session-based authentication
│ ├─ Server stores session data (Redis/DB)
│ ├─ Session ID in httpOnly cookie
│ └─ Best for: monoliths, SSR apps, admin panels
│
├─ API consumed by multiple clients?
│ └─ JWT (JSON Web Tokens)
│ ├─ Stateless, self-contained tokens
│ ├─ Access token (short-lived) + refresh token (long-lived)
│ └─ Best for: microservices, mobile apps, SPAs via BFF
│
├─ Service-to-service communication?
│ └─ API keys or Client Credentials (OAuth2)
│ ├─ API keys: simple, scoped, rotatable
│ ├─ Client Credentials: OAuth2 standard, token-based
│ └─ Best for: internal services, third-party integrations
│
├─ Third-party login (Google, GitHub, etc.)?
│ └─ OAuth2 / OpenID Connect
│ ├─ Authorization Code + PKCE for web/mobile
│ ├─ Delegate identity to trusted providers
│ └─ Best for: consumer apps, social login
│
├─ Passwordless authentication?
│ └─ Passkeys (WebAuthn) or Magic Links
│ ├─ Passkeys: phishing-resistant, biometric/hardware
│ ├─ Magic links: email-based, time-limited
│ └─ Best for: high-security, modern UX
│
└─ Internal tool / staff app with an existing IdP?
└─ Identity-aware proxy (Cloudflare Access)
├─ Authn enforced at the edge, before your origin
├─ Origin verifies the proxy's signed JWT (never a bare header)
└─ Best for: admin panels, partner portals, not consumer signup使用此决策树为你的用例选择合适的认证策略。
What are you building?
│
├─ Traditional web application (server-rendered)?
│ └─ Session-based authentication
│ ├─ Server stores session data (Redis/DB)
│ ├─ Session ID in httpOnly cookie
│ └─ Best for: monoliths, SSR apps, admin panels
│
├─ API consumed by multiple clients?
│ └─ JWT (JSON Web Tokens)
│ ├─ Stateless, self-contained tokens
│ ├─ Access token (short-lived) + refresh token (long-lived)
│ └─ Best for: microservices, mobile apps, SPAs via BFF
│
├─ Service-to-service communication?
│ └─ API keys or Client Credentials (OAuth2)
│ ├─ API keys: simple, scoped, rotatable
│ ├─ Client Credentials: OAuth2 standard, token-based
│ └─ Best for: internal services, third-party integrations
│
├─ Third-party login (Google, GitHub, etc.)?
│ └─ OAuth2 / OpenID Connect
│ ├─ Authorization Code + PKCE for web/mobile
│ ├─ Delegate identity to trusted providers
│ └─ Best for: consumer apps, social login
│
├─ Passwordless authentication?
│ └─ Passkeys (WebAuthn) or Magic Links
│ ├─ Passkeys: phishing-resistant, biometric/hardware
│ ├─ Magic links: email-based, time-limited
│ └─ Best for: high-security, modern UX
│
└─ Internal tool / staff app with an existing IdP?
└─ Identity-aware proxy (Cloudflare Access)
├─ Authn enforced at the edge, before your origin
├─ Origin verifies the proxy's signed JWT (never a bare header)
└─ Best for: admin panels, partner portals, not consumer signupJWT Quick Reference
JWT快速参考
Structure
结构
Header.Payload.Signature
Header: { "alg": "RS256", "typ": "JWT" }
Payload: { "iss": "auth.example.com", "sub": "user_123", ... }
Signature: RSASHA256(base64(header) + "." + base64(payload), privateKey)Header.Payload.Signature
Header: { "alg": "RS256", "typ": "JWT" }
Payload: { "iss": "auth.example.com", "sub": "user_123", ... }
Signature: RSASHA256(base64(header) + "." + base64(payload), privateKey)Common Claims
常见声明
| Claim | Name | Purpose | Example |
|---|---|---|---|
| Issuer | Who issued the token | |
| Subject | Who the token represents | |
| Expiration | When the token expires | |
| Issued At | When the token was created | |
| Audience | Intended recipient(s) | |
| JWT ID | Unique token identifier | |
| Not Before | Token not valid before this time | |
| Claim | 名称 | 用途 | 示例 |
|---|---|---|---|
| 签发者 | 令牌的签发方 | |
| 主体 | 令牌所代表的对象 | |
| 过期时间 | 令牌的过期时间 | |
| 签发时间 | 令牌的创建时间 | |
| 受众 | 令牌的预期接收方 | |
| JWT ID | 令牌的唯一标识符 | |
| 生效时间 | 令牌在此时间之前无效 | |
Signing Algorithms
签名算法
| Algorithm | Type | Key | Use When |
|---|---|---|---|
| RS256 | Asymmetric (RSA) | Public/private key pair | Distributed systems, multiple verifiers |
| ES256 | Asymmetric (ECDSA) | Public/private key pair | Same as RS256, smaller keys/signatures |
| HS256 | Symmetric (HMAC) | Shared secret | Single service, simple setups |
Rule of thumb: Use asymmetric (RS256/ES256) when the token issuer and verifier are different services. Use HS256 only when a single service both creates and verifies tokens.
| Algorithm | 类型 | 密钥 | 适用场景 |
|---|---|---|---|
| RS256 | 非对称(RSA) | 公钥/私钥对 | 分布式系统、多验证方 |
| ES256 | 非对称(ECDSA) | 公钥/私钥对 | 与RS256相同,密钥/签名更小 |
| HS256 | 对称(HMAC) | 共享密钥 | 单一服务、简单场景 |
经验法则: 当令牌签发方与验证方为不同服务时,使用非对称算法(RS256/ES256)。仅当单一服务同时创建和验证令牌时,才使用HS256。
Access + Refresh Token Pattern
访问令牌 + 刷新令牌模式
┌──────────┐ ┌──────────┐
│ Client │─── login ────────>│ Auth │
│ │<── access (15m) ──│ Server │
│ │<── refresh (7d) ──│ │
│ │ └──────────┘
│ │─── API call ─────>┌──────────┐
│ │ (access token) │ Resource │
│ │<── response ──────│ Server │
│ │ └──────────┘
│ │─── access expired │ │
│ │─── refresh ──────>│ Auth │
│ │<── new access ────│ Server │
│ │<── new refresh ───│ (rotate)│
└──────────┘ └──────────┘- Access token: Short-lived (5-15 minutes), used for API calls
- Refresh token: Long-lived (7-30 days), used to get new access tokens
- Rotation: Issue a new refresh token with each use, invalidate the old one
- Family detection: Track refresh token lineage; if a revoked token is reused, invalidate the entire family
┌──────────┐ ┌──────────┐
│ Client │─── login ────────>│ Auth │
│ │<── access (15m) ──│ Server │
│ │<── refresh (7d) ──│ │
│ │ └──────────┘
│ │─── API call ─────>┌──────────┐
│ │ (access token) │ Resource │
│ │<── response ──────│ Server │
│ │ └──────────┘
│ │─── access expired │ │
│ │─── refresh ──────>│ Auth │
│ │<── new access ────│ Server │
│ │<── new refresh ───│ (rotate)│
└──────────┘ └──────────┘- 访问令牌: 短有效期(5-15分钟),用于API调用
- 刷新令牌: 长有效期(7-30天),用于获取新的访问令牌
- 轮换: 每次使用时签发新的刷新令牌,作废旧令牌
- 家族检测: 跟踪刷新令牌谱系;如果作废的令牌被复用,则作废整个谱系的令牌
OAuth2 Flow Decision Tree
OAuth2流程决策树
What type of client?
│
├─ Web app with backend (Next.js, Rails, Django)?
│ └─ Authorization Code + PKCE
│ ├─ Redirect user to authorization server
│ ├─ Receive code at callback URL
│ ├─ Exchange code for tokens server-side
│ └─ PKCE prevents code interception attacks
│
├─ SPA (React, Vue) without backend?
│ └─ Authorization Code + PKCE (via BFF)
│ ├─ Use a Backend-for-Frontend to handle tokens
│ ├─ Never store tokens in browser-accessible storage
│ └─ BFF proxies API calls with token attached
│
├─ Mobile app (iOS, Android)?
│ └─ Authorization Code + PKCE
│ ├─ Use custom URI scheme or universal links for redirect
│ ├─ PKCE is mandatory (public client)
│ └─ Store tokens in secure enclave/keystore
│
├─ Server-to-server (no user)?
│ └─ Client Credentials
│ ├─ Authenticate with client_id + client_secret
│ ├─ No user context, service-level access
│ └─ Token cached until expiry
│
├─ CLI tool or smart TV?
│ └─ Device Code
│ ├─ Display code and URL to user
│ ├─ User authenticates on another device
│ ├─ CLI/TV polls for completion
│ └─ Good UX for input-constrained devices
│
└─ Microservice acting on behalf of a user?
└─ Token Exchange (RFC 8693)
├─ Exchange user's token for a scoped downstream token
├─ Maintains user context across services
└─ Use `act` claim for delegation chainWhat type of client?
│
├─ Web app with backend (Next.js, Rails, Django)?
│ └─ Authorization Code + PKCE
│ ├─ Redirect user to authorization server
│ ├─ Receive code at callback URL
│ ├─ Exchange code for tokens server-side
│ └─ PKCE prevents code interception attacks
│
├─ SPA (React, Vue) without backend?
│ └─ Authorization Code + PKCE (via BFF)
│ ├─ Use a Backend-for-Frontend to handle tokens
│ ├─ Never store tokens in browser-accessible storage
│ └─ BFF proxies API calls with token attached
│
├─ Mobile app (iOS, Android)?
│ └─ Authorization Code + PKCE
│ ├─ Use custom URI scheme or universal links for redirect
│ ├─ PKCE is mandatory (public client)
│ └─ Store tokens in secure enclave/keystore
│
├─ Server-to-server (no user)?
│ └─ Client Credentials
│ ├─ Authenticate with client_id + client_secret
│ ├─ No user context, service-level access
│ └─ Token cached until expiry
│
├─ CLI tool or smart TV?
│ └─ Device Code
│ ├─ Display code and URL to user
│ ├─ User authenticates on another device
│ ├─ CLI/TV polls for completion
│ └─ Good UX for input-constrained devices
│
└─ Microservice acting on behalf of a user?
└─ Token Exchange (RFC 8693)
├─ Exchange user's token for a scoped downstream token
├─ Maintains user context across services
└─ Use `act` claim for delegation chainAuthorization Model Decision Tree
授权模型决策树
How complex are your access control needs?
│
├─ Simple: just "can user X do action Y"?
│ └─ Permission-based (direct)
│ ├─ user_permissions table
│ ├─ Simple to implement, hard to scale
│ └─ Good for: small apps, prototypes
│
├─ Users grouped into roles with fixed permissions?
│ └─ RBAC (Role-Based Access Control)
│ ├─ Roles: admin, editor, viewer
│ ├─ Each role has a set of permissions
│ ├─ Users assigned one or more roles
│ └─ Good for: most apps, admin panels, team tools
│
├─ Decisions depend on attributes (time, location, resource owner)?
│ └─ ABAC (Attribute-Based Access Control)
│ ├─ Policies evaluate subject + resource + environment attributes
│ ├─ "Allow if user.department == resource.department AND time < 17:00"
│ ├─ Flexible but complex
│ └─ Good for: enterprise, compliance-heavy, context-dependent access
│
└─ Access based on relationships (owner, parent, shared with)?
└─ ReBAC (Relationship-Based Access Control)
├─ Google Zanzibar model
├─ Tuples: user:alice#viewer@document:report
├─ Supports inheritance: folder viewer → document viewer
├─ Tools: OpenFGA, SpiceDB, Ory Keto
└─ Good for: file sharing, nested resources, social featuresHow complex are your access control needs?
│
├─ Simple: just "can user X do action Y"?
│ └─ Permission-based (direct)
│ ├─ user_permissions table
│ ├─ Simple to implement, hard to scale
│ └─ Good for: small apps, prototypes
│
├─ Users grouped into roles with fixed permissions?
│ └─ RBAC (Role-Based Access Control)
│ ├─ Roles: admin, editor, viewer
│ ├─ Each role has a set of permissions
│ ├─ Users assigned one or more roles
│ └─ Good for: most apps, admin panels, team tools
│
├─ Decisions depend on attributes (time, location, resource owner)?
│ └─ ABAC (Attribute-Based Access Control)
│ ├─ Policies evaluate subject + resource + environment attributes
│ ├─ "Allow if user.department == resource.department AND time < 17:00"
│ ├─ Flexible but complex
│ └─ Good for: enterprise, compliance-heavy, context-dependent access
│
└─ Access based on relationships (owner, parent, shared with)?
└─ ReBAC (Relationship-Based Access Control)
├─ Google Zanzibar model
├─ Tuples: user:alice#viewer@document:report
├─ Supports inheritance: folder viewer → document viewer
├─ Tools: OpenFGA, SpiceDB, Ory Keto
└─ Good for: file sharing, nested resources, social featuresSession Management Quick Reference
会话管理快速参考
Cookie Security Settings
Cookie安全设置
| Setting | Value | Purpose |
|---|---|---|
| | Cookie sent only for same-site requests (best CSRF protection) |
| | Cookie sent for top-level navigations (good default) |
| | Cookie sent for cross-site requests (requires |
| | Cookie only sent over HTTPS |
| | Cookie not accessible via JavaScript (prevents XSS theft) |
| N/A | Requires Secure, no Domain, Path=/ (strictest) |
| N/A | Requires Secure flag |
| seconds | Cookie lifetime (prefer over |
| | Scope cookie to path (usually |
| 设置 | 值 | 用途 |
|---|---|---|
| | Cookie仅在同站点请求中发送(最佳CSRF防护) |
| | Cookie在顶级导航中发送(良好默认值) |
| | Cookie在跨站点请求中发送(需要 |
| | Cookie仅通过HTTPS发送 |
| | Cookie无法通过JavaScript访问(防止XSS窃取) |
| N/A | 需要Secure,无Domain,Path=/(最严格) |
| N/A | 需要Secure标志 |
| 秒 | Cookie有效期(优先于 |
| | Cookie的作用路径(通常为 |
Recommended Cookie Configuration
推荐的Cookie配置
Set-Cookie: __Host-session=abc123;
Secure;
HttpOnly;
SameSite=Lax;
Max-Age=86400;
Path=/Set-Cookie: __Host-session=abc123;
Secure;
HttpOnly;
SameSite=Lax;
Max-Age=86400;
Path=/Session Expiry Strategies
会话过期策略
| Strategy | Typical Value | Notes |
|---|---|---|
| Idle timeout | 15-30 minutes | Reset on each request |
| Absolute timeout | 8-24 hours | Force re-authentication |
| Sliding window | 30 min idle, 8h max | Best balance |
| Remember me | 30 days | Extended session, reduced privileges |
| 策略 | 典型值 | 说明 |
|---|---|---|
| 空闲超时 | 15-30分钟 | 每次请求时重置 |
| 绝对超时 | 8-24小时 | 强制重新认证 |
| 滑动窗口 | 30分钟空闲,8小时最大 | 最佳平衡 |
| 记住我 | 30天 | 延长会话,降低权限 |
Password Handling Quick Reference
密码处理快速参考
Hashing Algorithms
哈希算法
| Algorithm | Verdict | Notes |
|---|---|---|
| argon2id | BEST | Memory-hard, resists GPU attacks, recommended by OWASP |
| bcrypt | GOOD | Battle-tested, cost factor 12+, 72-byte input limit |
| scrypt | GOOD | Memory-hard, less common library support |
| PBKDF2 | ACCEPTABLE | FIPS compliant, use 600k+ iterations with SHA-256 |
| SHA-256/512 | BAD | Too fast, no salt built-in, easily brute-forced |
| MD5 | NEVER | Broken, rainbow tables widely available |
| Algorithm | 结论 | 说明 |
|---|---|---|
| argon2id | 最佳 | 内存密集型,抵御GPU攻击,OWASP推荐 |
| bcrypt | 良好 | 久经考验,成本因子12+,72字节输入限制 |
| scrypt | 良好 | 内存密集型,库支持较少 |
| PBKDF2 | 可接受 | FIPS合规,使用600k+迭代次数和SHA-256 |
| SHA-256/512 | 糟糕 | 速度过快,无内置盐值,易被暴力破解 |
| MD5 | 绝不使用 | 已被破解,彩虹表广泛可用 |
Password Rules (NIST 800-63B)
密码规则(NIST 800-63B)
| Rule | Guidance |
|---|---|
| Minimum length | 8 characters (12+ recommended) |
| Maximum length | At least 64 characters |
| Complexity rules | Do NOT require special chars/uppercase/numbers |
| Breached password check | Check against known breached passwords (HaveIBeenPwned API) |
| Password hints | Do NOT allow |
| Forced rotation | Do NOT force periodic changes (only on breach) |
| Paste into password field | ALLOW (supports password managers) |
| 规则 | 指南 |
|---|---|
| 最小长度 | 8个字符(推荐12+) |
| 最大长度 | 至少64个字符 |
| 复杂度规则 | 不要要求特殊字符/大写字母/数字 |
| 泄露密码检查 | 对照已知泄露密码检查(HaveIBeenPwned API) |
| 密码提示 | 不允许 |
| 强制轮换 | 不要强制定期更改(仅在泄露时更改) |
| 粘贴到密码字段 | 允许(支持密码管理器) |
Rate Limiting Login Attempts
登录尝试速率限制
| Attempt | Response |
|---|---|
| 1-5 | Normal login |
| 6-10 | CAPTCHA required |
| 11-20 | Progressive delays (2s, 4s, 8s...) |
| 20+ | Temporary account lockout (15-30 min) |
Important: Use consistent response times for both success and failure to prevent timing-based username enumeration.
| 尝试次数 | 响应 |
|---|---|
| 1-5 | 正常登录 |
| 6-10 | 需要CAPTCHA |
| 11-20 | 渐进式延迟(2秒、4秒、8秒...) |
| 20+ | 临时账户锁定(15-30分钟) |
重要提示: 成功和失败响应使用一致的响应时间,防止基于计时的用户名枚举。
MFA Quick Reference
MFA快速参考
Methods Ranked by Security
按安全性排序的方法
| Method | Security | UX | Notes |
|---|---|---|---|
| WebAuthn/Passkeys | Highest | Good | Phishing-resistant, hardware-backed |
| TOTP (Authenticator) | High | Medium | App-based (Google/Microsoft Authenticator) |
| Push notifications | High | Good | Requires mobile app |
| Email OTP | Medium | Medium | Depends on email security |
| SMS OTP | Low | Easy | SIM swap vulnerable, use as fallback only |
| 方法 | 安全性 | 用户体验 | 说明 |
|---|---|---|---|
| WebAuthn/Passkeys | 最高 | 良好 | 防钓鱼,硬件支持 |
| TOTP(认证器) | 高 | 中等 | 基于应用(Google/Microsoft Authenticator) |
| 推送通知 | 高 | 良好 | 需要移动应用 |
| 邮箱OTP | 中等 | 中等 | 依赖邮箱安全性 |
| 短信OTP | 低 | 简单 | 易受SIM卡交换攻击,仅用作备用 |
TOTP Implementation Checklist
TOTP实施清单
- Generate 160-bit secret (base32 encoded)
- Build otpauth:// URI with issuer and account
- Display QR code for authenticator scanning
- Require verification of first code before enabling
- Accept current window +/- 1 (30-second steps)
- Generate 8-10 single-use backup codes
- Hash backup codes before storing
- Allow recovery via verified identity
- 生成160位密钥(base32编码)
- 构建包含签发者和账户的otpauth:// URI
- 显示二维码供认证器扫描
- 启用前要求验证第一个验证码
- 接受当前窗口±1(30秒步长)
- 生成8-10个一次性备份码
- 备份码哈希后存储
- 允许通过已验证身份恢复
Passkey/WebAuthn Checklist
Passkey/WebAuthn实施清单
- Generate cryptographic challenge on server
- Set relying party ID (your domain)
- Store credential public key and ID
- Verify signature on authentication
- Support multiple credentials per user
- Handle platform vs cross-platform authenticators
- Provide fallback auth method
- 在服务器上生成加密挑战
- 设置依赖方ID(你的域名)
- 存储凭证公钥和ID
- 验证认证时的签名
- 支持每个用户多个凭证
- 处理平台型与跨平台型认证器
- 提供备用认证方法
Identity-Aware Proxy Quick Reference
身份感知代理快速参考
When authn is delegated to a proxy edge (Cloudflare Access, Google IAP, oauth2-proxy), two invariants carry the whole model:
- Verify the assertion. The proxy's identity header is a signed JWT — verify signature + issuer + per-application audience against the proxy's JWKS on every request. Never trust the plain email convenience headers.
- Close every path around the proxy. The header is only meaningful if the proxy is the only way to reach the origin (, firewalled origin, or tunnel). An open origin makes any header forgeable.
workers_dev = false
Proxy edge (authn) ──JWT header──> Origin verifies JWT ──> app user lookup ──> role/scope binding
│ │ 403 on any failure │ 403 if no row (server-side)
└ IdP / OTP login, sessions └ cached JWKS, └ proxy admits ≠ app authorizes
rate limits, bot defense refetch on unknown kidMachine routes (webhooks, ingest) get Service-Auth/Bypass at the edge + bearer keys at the origin, mounted outside the human-auth middleware. Full treatment: .
references/cloudflare-access.md当认证委托给边缘代理(Cloudflare Access、Google IAP、oauth2-proxy)时,两个不变原则支撑整个模型:
- 验证断言。 代理的身份头是一个已签名的JWT —— 在每次请求时验证签名 + 签发者 + 每个应用的受众,对照代理的JWKS。永远不要信任纯邮箱便捷头。
- 关闭代理周围的所有路径。 只有当代理是到达源站的唯一途径时,头才有意义(、源站防火墙或隧道)。开放的源站会使任何头都可伪造。
workers_dev = false
Proxy edge (authn) ──JWT header──> Origin verifies JWT ──> app user lookup ──> role/scope binding
│ │ 403 on any failure │ 403 if no row (server-side)
└ IdP / OTP login, sessions └ cached JWKS, └ proxy admits ≠ app authorizes
rate limits, bot defense refetch on unknown kid机器路由(Webhook、数据摄入)在边缘使用服务认证/绕过 + 在源站使用Bearer密钥,挂载在人类认证中间件之外。详细说明:。
references/cloudflare-access.mdCommon Gotchas
常见陷阱
| Gotcha | Why It's Dangerous | Fix |
|---|---|---|
| JWT stored in localStorage | XSS can steal tokens, no expiry enforcement by browser | Use httpOnly cookies or BFF pattern |
| Missing PKCE in OAuth2 | Authorization code interception attacks possible | Always use PKCE, even for confidential clients |
| Role explosion in RBAC | Hundreds of roles become unmanageable | Move to ABAC or ReBAC for complex scenarios |
| String comparison for tokens | Timing attacks reveal token value character by character | Use constant-time comparison ( |
| No token revocation strategy | Cannot invalidate compromised JWTs before expiry | Short expiry + refresh tokens, or maintain a blocklist |
CORS with | | Specify exact origin, set |
| Browser silently rejects the cookie | Always pair |
| Refresh token reuse without detection | Stolen refresh tokens grant indefinite access | Rotate refresh tokens, detect reuse (token families) |
| Using OAuth2 Implicit grant | Tokens exposed in URL fragment, no refresh tokens | Use Authorization Code + PKCE instead (Implicit is deprecated) |
| Password in URL or logs | URLs are logged by proxies, browsers, and servers | Always send credentials in request body or headers |
| Missing CSRF protection with cookies | Cookie-based auth is vulnerable to cross-site request forgery | Use SameSite cookies + CSRF tokens for state-changing ops |
| Long-lived access tokens (hours/days) | Large attack window if token is compromised | Keep access tokens to 5-15 minutes, use refresh tokens |
| Storing API keys in plaintext | Database breach exposes all keys | Hash stored keys (SHA-256 of key), store prefix for lookup |
Not validating JWT | Token meant for Service A accepted by Service B | Always validate |
| Session fixation | Attacker sets session ID before login, then hijacks it | Regenerate session ID after authentication |
| Hardcoded secrets in code | Secrets leak via source control | Use environment variables or secret managers (Vault, AWS SSM) |
| Trusting an identity-aware proxy's plain email header | Headers are attacker-settable on any unproxied path | Verify the proxy's signed JWT (sig + issuer + audience); close every path around the proxy |
| Auth-library middleware as the only session check | Framework middleware can be bypassed (Next.js CVE-2025-29927 class) | Re-check the session in the data-access layer / route handlers |
| 陷阱 | 危险原因 | 修复方案 |
|---|---|---|
| JWT存储在localStorage中 | XSS可窃取令牌,浏览器无法强制过期 | 使用httpOnly Cookie或BFF模式 |
| OAuth2中缺少PKCE | 可能发生授权码拦截攻击 | 始终使用PKCE,即使是机密客户端 |
| RBAC中的角色爆炸 | 数百个角色变得难以管理 | 对于复杂场景,迁移到ABAC或ReBAC |
| 令牌的字符串比较 | 计时攻击会逐字符泄露令牌值 | 使用常量时间比较( |
| 无令牌撤销策略 | 无法在过期前作废已泄露的JWT | 短有效期 + 刷新令牌,或维护黑名单 |
带 | | 指定精确源站,设置 |
| 浏览器会静默拒绝Cookie | 始终将 |
| 刷新令牌复用而未检测 | 被盗的刷新令牌会授予无限访问权限 | 轮换刷新令牌,检测复用(令牌家族) |
| 使用OAuth2隐式授权 | 令牌暴露在URL片段中,无刷新令牌 | 使用授权码 + PKCE替代(隐式授权已弃用) |
| 密码在URL或日志中 | URL会被代理、浏览器和服务器记录 | 始终在请求体或头中发送凭证 |
| Cookie认证缺少CSRF防护 | 基于Cookie的认证易受跨站请求伪造攻击 | 使用SameSite Cookie + CSRF令牌处理状态变更操作 |
| 长有效期访问令牌(数小时/天) | 令牌泄露后攻击窗口大 | 将访问令牌有效期保持在5-15分钟,使用刷新令牌 |
| API密钥明文存储 | 数据库泄露会暴露所有密钥 | 哈希存储的密钥(密钥的SHA-256),存储前缀用于查找 |
未验证JWT的 | 为服务A签发的令牌被服务B接受 | 始终验证 |
| 会话固定 | 攻击者在登录前设置会话ID,然后劫持会话 | 认证后重新生成会话ID |
| 代码中硬编码密钥 | 密钥会通过源代码控制泄露 | 使用环境变量或密钥管理器(Vault、AWS SSM) |
| 信任身份感知代理的纯邮箱头 | 在任何未代理的路径上,头可被攻击者设置 | 验证代理的已签名JWT(签名 + 签发者 + 受众);关闭代理周围的所有路径 |
| 仅使用认证库中间件作为会话检查 | 框架中间件可能被绕过(Next.js CVE-2025-29927类漏洞) | 在数据访问层/路由处理程序中重新检查会话 |
Reference Files
参考文件
| File | Contents | Lines |
|---|---|---|
| JWT structure, signing, sessions, cookies, CSRF, storage | ~650 |
| OAuth2 flows, OIDC, provider integration, social login | ~700 |
| RBAC, ABAC, ReBAC, RLS, multi-tenant, audit logging | ~600 |
| Password hashing, MFA, rate limiting, API keys, reset flows | ~550 |
| Identity-aware proxies via Cloudflare Access: app/policy anatomy, token claims, JWT verification, closed-origin precondition, service auth, sessions/logout/SPA, local dev | ~330 |
| Better Auth library: server/client setup, adapters, session model, social login, plugin catalog (passkey/2FA/org/SSO), Hono integration, migration | ~240 |
| 文件 | 内容 | 行数 |
|---|---|---|
| JWT结构、签名、会话、Cookie、CSRF、存储 | ~650 |
| OAuth2流程、OIDC、提供商集成、社交登录 | ~700 |
| RBAC、ABAC、ReBAC、RLS、多租户、审计日志 | ~600 |
| 密码哈希、MFA、速率限制、API密钥、重置流程 | ~550 |
| 通过Cloudflare Access实现身份感知代理:应用/策略结构、令牌声明、JWT验证、封闭源站前提、服务认证、会话/登出/SPA、本地开发 | ~330 |
| Better Auth库:服务端/客户端设置、适配器、会话模型、社交登录、插件目录(passkey/2FA/org/SSO)、Hono集成、迁移 | ~240 |
See Also
另请参阅
- security-ops - Broader security patterns: OWASP, headers, input validation, encryption
- api-design-ops - API design including authentication endpoints, rate limiting
- postgres-ops - Row-level security (RLS) policies for database authorization
- cloudflare-ops - Workers runtime, wrangler config, secrets, deploy mechanics behind an Access-fronted origin
- security-ops - 更广泛的安全模式:OWASP、头信息、输入验证、加密
- api-design-ops - API设计,包括认证端点、速率限制
- postgres-ops - 用于数据库授权的行级安全(RLS)策略
- cloudflare-ops - Workers运行时、wrangler配置、密钥、Access前端源站背后的部署机制