auth-ops

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth 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 signup

JWT 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

常见声明

ClaimNamePurposeExample
iss
IssuerWho issued the token
"auth.example.com"
sub
SubjectWho the token represents
"user_123"
exp
ExpirationWhen the token expires
1700000000
(Unix timestamp)
iat
Issued AtWhen the token was created
1699999100
aud
AudienceIntended recipient(s)
"api.example.com"
jti
JWT IDUnique token identifier
"a1b2c3d4"
(for revocation)
nbf
Not BeforeToken not valid before this time
1699999100
Claim名称用途示例
iss
签发者令牌的签发方
"auth.example.com"
sub
主体令牌所代表的对象
"user_123"
exp
过期时间令牌的过期时间
1700000000
(Unix时间戳)
iat
签发时间令牌的创建时间
1699999100
aud
受众令牌的预期接收方
"api.example.com"
jti
JWT ID令牌的唯一标识符
"a1b2c3d4"
(用于撤销)
nbf
生效时间令牌在此时间之前无效
1699999100

Signing Algorithms

签名算法

AlgorithmTypeKeyUse When
RS256Asymmetric (RSA)Public/private key pairDistributed systems, multiple verifiers
ES256Asymmetric (ECDSA)Public/private key pairSame as RS256, smaller keys/signatures
HS256Symmetric (HMAC)Shared secretSingle 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 chain
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 chain

Authorization 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 features
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 features

Session Management Quick Reference

会话管理快速参考

Cookie Security Settings

Cookie安全设置

SettingValuePurpose
SameSite
Strict
Cookie sent only for same-site requests (best CSRF protection)
SameSite
Lax
Cookie sent for top-level navigations (good default)
SameSite
None
Cookie sent for cross-site requests (requires
Secure
)
Secure
true
Cookie only sent over HTTPS
HttpOnly
true
Cookie not accessible via JavaScript (prevents XSS theft)
__Host-
prefix
N/ARequires Secure, no Domain, Path=/ (strictest)
__Secure-
prefix
N/ARequires Secure flag
Max-Age
secondsCookie lifetime (prefer over
Expires
)
Path
/
Scope cookie to path (usually
/
)
设置用途
SameSite
Strict
Cookie仅在同站点请求中发送(最佳CSRF防护)
SameSite
Lax
Cookie在顶级导航中发送(良好默认值)
SameSite
None
Cookie在跨站点请求中发送(需要
Secure
Secure
true
Cookie仅通过HTTPS发送
HttpOnly
true
Cookie无法通过JavaScript访问(防止XSS窃取)
__Host-
前缀
N/A需要Secure,无Domain,Path=/(最严格)
__Secure-
前缀
N/A需要Secure标志
Max-Age
Cookie有效期(优先于
Expires
Path
/
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

会话过期策略

StrategyTypical ValueNotes
Idle timeout15-30 minutesReset on each request
Absolute timeout8-24 hoursForce re-authentication
Sliding window30 min idle, 8h maxBest balance
Remember me30 daysExtended session, reduced privileges
策略典型值说明
空闲超时15-30分钟每次请求时重置
绝对超时8-24小时强制重新认证
滑动窗口30分钟空闲,8小时最大最佳平衡
记住我30天延长会话,降低权限

Password Handling Quick Reference

密码处理快速参考

Hashing Algorithms

哈希算法

AlgorithmVerdictNotes
argon2idBESTMemory-hard, resists GPU attacks, recommended by OWASP
bcryptGOODBattle-tested, cost factor 12+, 72-byte input limit
scryptGOODMemory-hard, less common library support
PBKDF2ACCEPTABLEFIPS compliant, use 600k+ iterations with SHA-256
SHA-256/512BADToo fast, no salt built-in, easily brute-forced
MD5NEVERBroken, 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)

RuleGuidance
Minimum length8 characters (12+ recommended)
Maximum lengthAt least 64 characters
Complexity rulesDo NOT require special chars/uppercase/numbers
Breached password checkCheck against known breached passwords (HaveIBeenPwned API)
Password hintsDo NOT allow
Forced rotationDo NOT force periodic changes (only on breach)
Paste into password fieldALLOW (supports password managers)
规则指南
最小长度8个字符(推荐12+)
最大长度至少64个字符
复杂度规则不要要求特殊字符/大写字母/数字
泄露密码检查对照已知泄露密码检查(HaveIBeenPwned API)
密码提示不允许
强制轮换不要强制定期更改(仅在泄露时更改)
粘贴到密码字段允许(支持密码管理器)

Rate Limiting Login Attempts

登录尝试速率限制

AttemptResponse
1-5Normal login
6-10CAPTCHA required
11-20Progressive 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

按安全性排序的方法

MethodSecurityUXNotes
WebAuthn/PasskeysHighestGoodPhishing-resistant, hardware-backed
TOTP (Authenticator)HighMediumApp-based (Google/Microsoft Authenticator)
Push notificationsHighGoodRequires mobile app
Email OTPMediumMediumDepends on email security
SMS OTPLowEasySIM 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:
  1. 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.
  2. Close every path around the proxy. The header is only meaningful if the proxy is the only way to reach the origin (
    workers_dev = false
    , firewalled origin, or tunnel). An open origin makes any header forgeable.
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
Machine 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)时,两个不变原则支撑整个模型:
  1. 验证断言。 代理的身份头是一个已签名的JWT —— 在每次请求时验证签名 + 签发者 + 每个应用的受众,对照代理的JWKS。永远不要信任纯邮箱便捷头。
  2. 关闭代理周围的所有路径。 只有当代理是到达源站的唯一途径时,头才有意义(
    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.md

Common Gotchas

常见陷阱

GotchaWhy It's DangerousFix
JWT stored in localStorageXSS can steal tokens, no expiry enforcement by browserUse httpOnly cookies or BFF pattern
Missing PKCE in OAuth2Authorization code interception attacks possibleAlways use PKCE, even for confidential clients
Role explosion in RBACHundreds of roles become unmanageableMove to ABAC or ReBAC for complex scenarios
String comparison for tokensTiming attacks reveal token value character by characterUse constant-time comparison (
crypto.timingSafeEqual
)
No token revocation strategyCannot invalidate compromised JWTs before expiryShort expiry + refresh tokens, or maintain a blocklist
CORS with
credentials: true
Access-Control-Allow-Origin: *
does not work with credentials
Specify exact origin, set
Access-Control-Allow-Credentials: true
SameSite=None
without
Secure
Browser silently rejects the cookieAlways pair
SameSite=None
with
Secure
flag
Refresh token reuse without detectionStolen refresh tokens grant indefinite accessRotate refresh tokens, detect reuse (token families)
Using OAuth2 Implicit grantTokens exposed in URL fragment, no refresh tokensUse Authorization Code + PKCE instead (Implicit is deprecated)
Password in URL or logsURLs are logged by proxies, browsers, and serversAlways send credentials in request body or headers
Missing CSRF protection with cookiesCookie-based auth is vulnerable to cross-site request forgeryUse SameSite cookies + CSRF tokens for state-changing ops
Long-lived access tokens (hours/days)Large attack window if token is compromisedKeep access tokens to 5-15 minutes, use refresh tokens
Storing API keys in plaintextDatabase breach exposes all keysHash stored keys (SHA-256 of key), store prefix for lookup
Not validating JWT
aud
claim
Token meant for Service A accepted by Service BAlways validate
aud
matches your service identifier
Session fixationAttacker sets session ID before login, then hijacks itRegenerate session ID after authentication
Hardcoded secrets in codeSecrets leak via source controlUse environment variables or secret managers (Vault, AWS SSM)
Trusting an identity-aware proxy's plain email headerHeaders are attacker-settable on any unproxied pathVerify the proxy's signed JWT (sig + issuer + audience); close every path around the proxy
Auth-library middleware as the only session checkFramework 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
令牌的字符串比较计时攻击会逐字符泄露令牌值使用常量时间比较(
crypto.timingSafeEqual
无令牌撤销策略无法在过期前作废已泄露的JWT短有效期 + 刷新令牌,或维护黑名单
credentials: true
的CORS
Access-Control-Allow-Origin: *
不适用于凭证
指定精确源站,设置
Access-Control-Allow-Credentials: true
SameSite=None
不带
Secure
浏览器会静默拒绝Cookie始终将
SameSite=None
Secure
标志配对使用
刷新令牌复用而未检测被盗的刷新令牌会授予无限访问权限轮换刷新令牌,检测复用(令牌家族)
使用OAuth2隐式授权令牌暴露在URL片段中,无刷新令牌使用授权码 + PKCE替代(隐式授权已弃用)
密码在URL或日志中URL会被代理、浏览器和服务器记录始终在请求体或头中发送凭证
Cookie认证缺少CSRF防护基于Cookie的认证易受跨站请求伪造攻击使用SameSite Cookie + CSRF令牌处理状态变更操作
长有效期访问令牌(数小时/天)令牌泄露后攻击窗口大将访问令牌有效期保持在5-15分钟,使用刷新令牌
API密钥明文存储数据库泄露会暴露所有密钥哈希存储的密钥(密钥的SHA-256),存储前缀用于查找
未验证JWT的
aud
声明
为服务A签发的令牌被服务B接受始终验证
aud
与你的服务标识符匹配
会话固定攻击者在登录前设置会话ID,然后劫持会话认证后重新生成会话ID
代码中硬编码密钥密钥会通过源代码控制泄露使用环境变量或密钥管理器(Vault、AWS SSM)
信任身份感知代理的纯邮箱头在任何未代理的路径上,头可被攻击者设置验证代理的已签名JWT(签名 + 签发者 + 受众);关闭代理周围的所有路径
仅使用认证库中间件作为会话检查框架中间件可能被绕过(Next.js CVE-2025-29927类漏洞)在数据访问层/路由处理程序中重新检查会话

Reference Files

参考文件

FileContentsLines
references/jwt-sessions.md
JWT structure, signing, sessions, cookies, CSRF, storage~650
references/oauth2-oidc.md
OAuth2 flows, OIDC, provider integration, social login~700
references/authorization.md
RBAC, ABAC, ReBAC, RLS, multi-tenant, audit logging~600
references/implementation.md
Password hashing, MFA, rate limiting, API keys, reset flows~550
references/cloudflare-access.md
Identity-aware proxies via Cloudflare Access: app/policy anatomy, token claims, JWT verification, closed-origin precondition, service auth, sessions/logout/SPA, local dev~330
references/better-auth.md
Better Auth library: server/client setup, adapters, session model, social login, plugin catalog (passkey/2FA/org/SSO), Hono integration, migration~240
文件内容行数
references/jwt-sessions.md
JWT结构、签名、会话、Cookie、CSRF、存储~650
references/oauth2-oidc.md
OAuth2流程、OIDC、提供商集成、社交登录~700
references/authorization.md
RBAC、ABAC、ReBAC、RLS、多租户、审计日志~600
references/implementation.md
密码哈希、MFA、速率限制、API密钥、重置流程~550
references/cloudflare-access.md
通过Cloudflare Access实现身份感知代理:应用/策略结构、令牌声明、JWT验证、封闭源站前提、服务认证、会话/登出/SPA、本地开发~330
references/better-auth.md
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前端源站背后的部署机制