auth-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Authentication Patterns

身份验证模式

Implement secure authentication with OAuth 2.1, Passkeys, and modern security standards.
使用OAuth 2.1、Passkeys和现代安全标准实现安全身份验证。

Overview

概述

  • Login/signup flows
  • JWT token management
  • Session security
  • OAuth 2.1 with PKCE
  • Passkeys/WebAuthn
  • Multi-factor authentication
  • Role-based access control
  • 登录/注册流程
  • JWT令牌管理
  • 会话安全
  • 带PKCE的OAuth 2.1
  • Passkeys/WebAuthn
  • 多因素身份验证
  • 基于角色的访问控制

Quick Reference

快速参考

Password Hashing (Argon2id)

密码哈希(Argon2id)

python
from argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
ph.verify(password_hash, password)
python
from argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
ph.verify(password_hash, password)

JWT Access Token

JWT访问令牌

python
import jwt
from datetime import datetime, timedelta, timezone
payload = {
    'user_id': user_id,
    'type': 'access',
    'exp': datetime.now(timezone.utc) + timedelta(minutes=15),
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
python
import jwt
from datetime import datetime, timedelta, timezone
payload = {
    'user_id': user_id,
    'type': 'access',
    'exp': datetime.now(timezone.utc) + timedelta(minutes=15),
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')

OAuth 2.1 with PKCE (Required)

带PKCE的OAuth 2.1(必填)

python
import hashlib, base64, secrets
code_verifier = secrets.token_urlsafe(64)
digest = hashlib.sha256(code_verifier.encode()).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode()
python
import hashlib, base64, secrets
code_verifier = secrets.token_urlsafe(64)
digest = hashlib.sha256(code_verifier.encode()).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode()

Session Security

会话安全

python
app.config['SESSION_COOKIE_SECURE'] = True      # HTTPS only
app.config['SESSION_COOKIE_HTTPONLY'] = True    # No JS access
app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
python
app.config['SESSION_COOKIE_SECURE'] = True      # 仅HTTPS可用
app.config['SESSION_COOKIE_HTTPONLY'] = True    # 禁止JS访问
app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'

Token Expiry ( Guidelines)

令牌有效期(指南)

Token TypeExpiryStorage
Access15 min - 1 hourMemory only
Refresh7-30 daysHTTPOnly cookie
令牌类型有效期存储方式
访问令牌15分钟-1小时仅内存存储
刷新令牌7-30天HTTPOnly Cookie

Anti-Patterns (FORBIDDEN)

反模式(禁止)

python
undefined
python
undefined

❌ NEVER store passwords in plaintext

❌ 绝对不要明文存储密码

user.password = request.form['password']
user.password = request.form['password']

❌ NEVER use implicit OAuth grant

❌ 绝对不要使用隐式OAuth授权

response_type=token # Deprecated in OAuth 2.1
response_type=token # OAuth 2.1中已弃用

❌ NEVER skip rate limiting on login

❌ 绝对不要跳过登录接口的速率限制

@app.route('/login') # No rate limit!
@app.route('/login') # 没有速率限制!

❌ NEVER reveal if email exists

❌ 绝对不要泄露邮箱是否存在

return "Email not found" # Information disclosure
return "Email not found" # 信息泄露

✅ ALWAYS use Argon2id or bcrypt

✅ 务必使用Argon2id或bcrypt

password_hash = ph.hash(password)
password_hash = ph.hash(password)

✅ ALWAYS use PKCE

✅ 务必使用PKCE

code_challenge=challenge&code_challenge_method=S256
code_challenge=challenge&code_challenge_method=S256

✅ ALWAYS rate limit auth endpoints

✅ 务必对身份验证接口做速率限制

@limiter.limit("5 per minute")
@limiter.limit("5 per minute")

✅ ALWAYS use generic error messages

✅ 务必使用通用错误提示

return "Invalid credentials"
undefined
return "Invalid credentials"
undefined

Key Decisions

关键决策

DecisionRecommendation
Password hashArgon2id > bcrypt
Access token expiry15 min - 1 hour
Refresh token expiry7-30 days with rotation
Session cookieHTTPOnly, Secure, SameSite=Strict
Rate limit5 attempts per minute
MFAPasskeys > TOTP > SMS
OAuth2.1 with PKCE (no implicit)
决策项推荐方案
密码哈希算法Argon2id > bcrypt
访问令牌有效期15分钟-1小时
刷新令牌有效期7-30天并支持轮换
会话CookieHTTPOnly、Secure、SameSite=Strict
速率限制每分钟最多5次尝试
多因素认证Passkeys > TOTP > SMS
OAuth带PKCE的2.1版本(禁止隐式授权)

Detailed Documentation

详细文档

ResourceDescription
references/oauth-2.1-passkeys.mdOAuth 2.1, PKCE, Passkeys/WebAuthn
examples/auth-implementations.mdComplete implementation examples
checklists/auth-checklist.mdSecurity checklist
scripts/auth-middleware-template.pyFlask/FastAPI middleware
资源说明
references/oauth-2.1-passkeys.mdOAuth 2.1、PKCE、Passkeys/WebAuthn相关内容
examples/auth-implementations.md完整实现示例
checklists/auth-checklist.md安全检查清单
scripts/auth-middleware-template.pyFlask/FastAPI中间件模板

Related Skills

相关技能

  • owasp-top-10
    - Security fundamentals
  • input-validation
    - Data validation
  • api-design-framework
    - API security
  • owasp-top-10
    - 安全基础知识
  • input-validation
    - 数据验证
  • api-design-framework
    - API安全

Capability Details

能力详情

password-hashing

password-hashing

Keywords: password, hashing, bcrypt, argon2, hash Solves:
  • Securely hash passwords with modern algorithms
  • Configure appropriate cost factors
  • Migrate legacy password hashes
关键词: password, hashing, bcrypt, argon2, hash 解决场景:
  • 使用现代算法安全地哈希密码
  • 配置合适的成本因子
  • 迁移旧版密码哈希

jwt-tokens

jwt-tokens

Keywords: JWT, token, access token, claims, jsonwebtoken Solves:
  • Generate and validate JWT access tokens
  • Implement proper token expiration
  • Handle token refresh securely
关键词: JWT, token, access token, claims, jsonwebtoken 解决场景:
  • 生成并验证JWT访问令牌
  • 实现合理的令牌过期机制
  • 安全处理令牌刷新

oauth2-pkce

oauth2-pkce

Keywords: OAuth, PKCE, OAuth 2.1, authorization code, code verifier Solves:
  • Implement OAuth 2.1 with PKCE flow
  • Secure authorization for SPAs and mobile apps
  • Handle OAuth provider integration
关键词: OAuth, PKCE, OAuth 2.1, authorization code, code verifier 解决场景:
  • 实现带PKCE的OAuth 2.1流程
  • 为单页应用和移动应用提供安全授权
  • 处理OAuth服务商集成

passkeys-webauthn

passkeys-webauthn

Keywords: passkey, WebAuthn, FIDO2, passwordless, biometric Solves:
  • Implement passwordless authentication
  • Configure WebAuthn registration and login
  • Support cross-device passkeys
关键词: passkey, WebAuthn, FIDO2, passwordless, biometric 解决场景:
  • 实现无密码身份验证
  • 配置WebAuthn注册与登录流程
  • 支持跨设备Passkeys

session-management

session-management

Keywords: session, cookie, session storage, logout, invalidate Solves:
  • Manage user sessions securely
  • Implement session invalidation on logout
  • Handle concurrent sessions
关键词: session, cookie, session storage, logout, invalidate 解决场景:
  • 安全管理用户会话
  • 实现登出时的会话失效
  • 处理并发会话

role-based-access

role-based-access

Keywords: RBAC, role, permission, authorization, access control Solves:
  • Implement role-based access control
  • Define permission hierarchies
  • Check authorization in routes
关键词: RBAC, role, permission, authorization, access control 解决场景:
  • 实现基于角色的访问控制
  • 定义权限层级
  • 在路由中检查授权状态