authentication

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
This skill guides implementation of secure authentication systems with persistent session management, token-based authentication, and comprehensive user identity handling.
The user provides authentication requirements: login, registration, session management, or user profile features. They may include context about security needs, user experience expectations, or integration requirements.
本技能指导你实现具备持久会话管理、基于令牌的认证以及全面用户身份处理的安全认证系统。
用户会提供认证需求:登录、注册、会话管理或用户资料功能。他们可能会包含安全需求、用户体验预期或集成要求等相关背景信息。

Authentication System Principles

认证系统原则

Before implementing, understand the security context and user experience requirements:
  • Security First: What data needs protection? What are the threat vectors?
  • User Experience: Balance security with friction - seamless for legitimate users, secure against attacks
  • Session Management: How long should sessions last? When should re-authentication be required?
  • Scalability: How will authentication scale with user growth?
  • Compliance: What regulatory requirements apply (GDPR, data protection, etc.)?
CRITICAL: Authentication is a security-critical component. Every decision must prioritize user data protection while maintaining a smooth user experience.
在实现之前,请先了解安全背景和用户体验要求:
  • 安全优先:哪些数据需要保护?存在哪些威胁向量?
  • 用户体验:在安全性与操作便捷性之间取得平衡——对合法用户流畅友好,对攻击行为严格防范
  • 会话管理:会话应持续多久?何时需要重新认证?
  • 可扩展性:认证系统如何随用户增长而扩展?
  • 合规性:需遵循哪些监管要求(GDPR、数据保护法规等)?
关键提示:认证是安全关键组件。每一项决策都必须在保障流畅用户体验的同时,优先保护用户数据。

Core Authentication Requirements

核心认证要求

User Registration

用户注册

  • Collect unique username and email address with format validation
  • Implement secure password hashing (never store plain text passwords)
  • Use industry-standard hashing algorithms with salt
  • Validate uniqueness of username and email before account creation
  • Optional profile information collection (names, profile picture)
  • Automatic account creation timestamp tracking
  • Email format and username validation required
  • 收集唯一用户名和邮箱地址,并验证格式有效性
  • 实现安全的密码哈希(绝不能存储明文密码)
  • 使用带盐的行业标准哈希算法
  • 在创建账户前验证用户名和邮箱的唯一性
  • 可选收集额外资料信息(姓名、头像)
  • 自动记录账户创建时间戳
  • 必须验证邮箱格式和用户名有效性

User Login

用户登录

  • Support authentication with either email or username
  • Verify credentials against securely stored hashes
  • Generate both access token (short-lived) and refresh token (long-lived)
  • Return user profile data with authentication tokens
  • Track failed login attempts to prevent brute force attacks
  • Implement account lockout after multiple failed attempts
  • Support session persistence across browser sessions
  • 支持使用邮箱或用户名进行认证
  • 对照安全存储的哈希值验证凭证
  • 同时生成Access Token(短期有效)和Refresh Token(长期有效)
  • 返回用户资料数据及认证令牌
  • 跟踪登录失败次数以防止暴力攻击
  • 多次失败尝试后触发账户锁定
  • 支持跨浏览器会话的会话持久化

Token Management

令牌管理

  • Access Token: Short expiration (15-60 minutes recommended)
    • Used for API authentication on each request
    • Contains minimal user identification data
    • Transmitted with each authenticated request
  • Refresh Token: Extended expiration (7-30 days recommended)
    • Used to obtain new access tokens
    • Stored securely on client side
    • Rotated on each refresh for security
  • Token Lifecycle:
    • Automatic token refresh before access token expiration
    • Token invalidation on explicit logout
    • Token blacklisting mechanism to prevent reuse of logged-out tokens
    • Secure token generation with sufficient entropy
  • Access Token:短期过期(建议15-60分钟)
    • 用于每次请求的API认证
    • 仅包含最少的用户识别数据
    • 随每个已认证请求传输
  • Refresh Token:长期过期(建议7-30天)
    • 用于获取新的Access Token
    • 在客户端安全存储
    • 每次刷新时轮换令牌以提升安全性
  • 令牌生命周期:
    • 在Access Token过期前自动刷新
    • 主动登出时使令牌失效
    • 实现令牌黑名单机制,防止已登出的令牌被重复使用
    • 使用足够熵值生成安全令牌

Session Persistence

会话持久化

  • Store authentication state in browser storage (localStorage or sessionStorage)
  • Automatically restore login state on page refresh
  • Validate stored tokens on application initialization
  • Clear all authentication state on logout
  • Handle token expiration gracefully with automatic refresh
  • Synchronize authentication state across browser tabs if needed
  • 在浏览器存储(localStorage或sessionStorage)中存储认证状态
  • 页面刷新时自动恢复登录状态
  • 应用初始化时验证存储的令牌
  • 登出时清除所有认证状态
  • 优雅处理令牌过期,自动刷新
  • 如需支持跨浏览器标签页同步认证状态

User Logout

用户登出

  • Invalidate current access token
  • Add refresh token to blacklist to prevent reuse
  • Clear all client-side authentication state
  • Clear any cached user data
  • Redirect to public area after successful logout
  • Revoke any active sessions on server side
  • 使当前Access Token失效
  • 将Refresh Token加入黑名单以防止重复使用
  • 清除客户端所有认证状态
  • 清除所有缓存的用户数据
  • 成功登出后重定向至公共区域
  • 在服务端撤销所有活跃会话

User Profile Management

用户资料管理

User Identity

用户身份

  • Display username, email, and registration date
  • Support profile picture upload during registration or later
  • Generate default avatar from user initials when no picture provided
  • Store and display user preferences and settings
  • Link user identity across all user-generated content
  • 显示用户名、邮箱和注册日期
  • 支持在注册时或后续上传头像
  • 当未提供头像时,根据用户姓名首字母生成默认头像
  • 存储并显示用户偏好和设置
  • 在所有用户生成内容中关联用户身份

Profile Picture Management

头像管理

  • Accept common image formats (JPEG, PNG)
  • Enforce maximum file size limits (5MB recommended)
  • Store optimized versions of uploaded images
  • Display profile pictures in navigation, content, and user references
  • Implement image validation to prevent malicious uploads
  • Generate thumbnails for different display contexts
  • 接受常见图片格式(JPEG、PNG)
  • 强制执行最大文件大小限制(建议5MB)
  • 存储上传图片的优化版本
  • 在导航栏、内容区域和用户引用处显示头像
  • 实现图片验证以防止恶意上传
  • 为不同展示场景生成缩略图

User Identity Display

用户身份展示

  • Show author information consistently across the platform
  • Display user avatars in navigation bar when authenticated
  • Link author profiles to their published content
  • Ensure consistent user identification across all features
  • 在平台内统一显示作者信息
  • 已认证时在导航栏显示用户头像
  • 将作者资料链接至其发布的内容
  • 确保所有功能中用户身份标识的一致性

Security Requirements

安全要求

Authentication Security

认证安全

  • Password Security:
    • Hash passwords with salt using industry-standard algorithms
    • Enforce minimum password strength requirements
    • Never log or display passwords in any form
    • Implement secure password reset mechanisms
  • Token Security:
    • Generate tokens with cryptographically secure random generation
    • Encrypt tokens in transit (HTTPS required)
    • Implement token expiration enforcement
    • Rotate refresh tokens regularly
    • Prevent token leakage through logging or error messages
  • Attack Prevention:
    • Rate limiting on authentication endpoints
    • Account lockout after multiple failed login attempts
    • CSRF protection on authentication state changes
    • SQL injection prevention through parameterized queries
    • XSS prevention in user-generated profile content
  • 密码安全:
    • 使用带盐的行业标准算法对密码进行哈希
    • 强制执行最低密码强度要求
    • 绝不记录或显示任何形式的密码
    • 实现安全的密码重置机制
  • 令牌安全:
    • 使用加密安全的随机生成方式生成令牌
    • 在传输过程中加密令牌(必须使用HTTPS)
    • 强制执行令牌过期规则
    • 定期轮换Refresh Token
    • 防止令牌通过日志或错误信息泄露
  • 攻击防护:
    • 对认证端点进行速率限制
    • 多次登录失败后触发账户锁定
    • 对认证状态变更实施CSRF防护
    • 通过参数化查询防止SQL注入
    • 对用户生成的资料内容实施XSS防护

Authorization Controls

授权控制

  • Verify resource ownership before allowing modifications
  • Implement permission checks on all protected endpoints
  • Prevent unauthorized access to user data
  • Validate user identity on every authenticated request
  • Separate authentication (who you are) from authorization (what you can do)
  • 在允许修改前验证资源所有权
  • 在所有受保护端点上实现权限检查
  • 防止未授权访问用户数据
  • 在每个已认证请求上验证用户身份
  • 将认证(你是谁)与授权(你能做什么)分离

Data Protection

数据保护

  • Encrypt sensitive data in transit (TLS/HTTPS)
  • Consider encryption at rest for sensitive user data
  • Implement secure session management
  • Sanitize all user inputs to prevent injection attacks
  • Output encoding for display of user-generated content
  • Validate file uploads thoroughly (type, size, content)
  • 在传输过程中加密敏感数据(TLS/HTTPS)
  • 考虑对敏感用户数据进行静态加密
  • 实现安全的会话管理
  • 清理所有用户输入以防止注入攻击
  • 对用户生成内容的显示进行输出编码
  • 全面验证文件上传(类型、大小、内容)

Implementation Guidelines

实现指南

Client-Side Implementation

客户端实现

  • Store tokens securely (avoid localStorage for highly sensitive apps, consider httpOnly cookies)
  • Implement automatic token refresh before expiration
  • Handle authentication state globally (context/state management)
  • Provide clear loading and error states during authentication
  • Clear all user data from memory on logout
  • Redirect unauthenticated users appropriately
  • Show authentication status clearly in UI
  • 安全存储令牌(高敏感应用避免使用localStorage,考虑使用httpOnly Cookie)
  • 在令牌过期前实现自动刷新
  • 全局管理认证状态(上下文/状态管理)
  • 认证过程中提供清晰的加载和错误状态
  • 登出时从内存中清除所有用户数据
  • 对未认证用户进行适当重定向
  • 在UI中清晰显示认证状态

Server-Side Implementation

服务端实现

  • Use established authentication libraries/frameworks
  • Implement token generation with proper randomness
  • Create token blacklist table for logout tracking
  • Index authentication-related database fields
  • Log authentication events for security monitoring
  • Implement rate limiting middleware
  • Handle concurrent login attempts properly
  • 使用成熟的认证库/框架
  • 实现具备适当随机性的令牌生成逻辑
  • 创建令牌黑名单表以跟踪登出记录
  • 为认证相关的数据库字段建立索引
  • 记录认证事件以用于安全监控
  • 实现速率限制中间件
  • 正确处理并发登录尝试

User Experience

用户体验

  • Minimize friction during registration (request only essential data)
  • Provide clear error messages without leaking security information
  • Show password strength indicators during registration
  • Implement "remember me" functionality securely
  • Auto-login after successful registration
  • Smooth transition between authenticated and unauthenticated states
  • Loading states during authentication operations
  • 最小化注册过程中的操作摩擦(仅请求必要数据)
  • 提供清晰的错误信息,且不泄露安全相关细节
  • 注册时显示密码强度指示器
  • 安全实现“记住我”功能
  • 注册成功后自动登录
  • 在已认证和未认证状态间平滑过渡
  • 认证操作过程中显示加载状态

Error Handling

错误处理

  • Generic error messages for authentication failures (don't specify if username or password was wrong)
  • Clear error messages for validation failures
  • Handle network errors gracefully
  • Retry logic for token refresh failures
  • Fallback to logout if token refresh repeatedly fails
  • User-friendly messages for account lockouts
  • 认证失败时返回通用错误信息(不要明确说明是用户名还是密码错误)
  • 验证失败时返回清晰的错误信息
  • 优雅处理网络错误
  • 令牌刷新失败时实现重试逻辑
  • 如果令牌刷新多次失败, fallback至登出
  • 账户锁定时显示用户友好的提示信息

Optional Advanced Features

可选高级功能

Consider implementing these features based on project requirements:
可根据项目需求考虑实现以下功能:

Enhanced Security

增强安全

  • Two-factor authentication (2FA/MFA)
  • Email verification for new accounts
  • Security questions for account recovery
  • IP-based access monitoring
  • Login notification emails
  • Suspicious activity detection
  • Device tracking and management
  • 双因素认证(2FA/MFA)
  • 新账户邮箱验证
  • 账户恢复安全问题
  • 基于IP的访问监控
  • 登录通知邮件
  • 可疑活动检测
  • 设备跟踪与管理

Enhanced User Experience

增强用户体验

  • Social authentication (OAuth providers)
  • Single sign-on (SSO) integration
  • Biometric authentication support
  • Passwordless authentication options
  • "Stay logged in" with secure implementation
  • 社交认证(OAuth提供商)
  • 单点登录(SSO)集成
  • 生物识别认证支持
  • 无密码认证选项
  • 安全实现“保持登录状态”功能

Profile Enhancements

资料增强

  • Public profile pages with user biography
  • Social media links integration
  • User activity history and statistics
  • Profile customization options
  • Follower/following system
  • User reputation or badge system
  • Profile privacy controls
  • 包含用户简介的公开资料页面
  • 社交媒体链接集成
  • 用户活动历史与统计
  • 资料自定义选项
  • 关注/粉丝系统
  • 用户声誉或徽章系统
  • 资料隐私控制

Session Management

会话管理

  • View active sessions
  • Remote session termination
  • Session timeout warnings
  • Multi-device session management
  • 查看活跃会话
  • 远程终止会话
  • 会话超时警告
  • 多设备会话管理

Testing Requirements

测试要求

Implement comprehensive testing for authentication:
  • Test all registration validation rules
  • Test successful and failed login scenarios
  • Test token generation and validation
  • Test token refresh mechanism
  • Test logout and token invalidation
  • Test password hashing and verification
  • Test rate limiting and brute force protection
  • Test session persistence across page reloads
  • Test concurrent session handling
  • Security testing for common vulnerabilities (SQL injection, XSS, CSRF)
为认证系统实现全面测试:
  • 测试所有注册验证规则
  • 测试登录成功和失败场景
  • 测试令牌生成与验证
  • 测试令牌刷新机制
  • 测试登出与令牌失效
  • 测试密码哈希与验证
  • 测试速率限制与暴力攻击防护
  • 测试跨页面刷新的会话持久化
  • 测试并发会话处理
  • 针对常见漏洞进行安全测试(SQL注入、XSS、CSRF)

Compliance Considerations

合规性考虑

Ensure authentication system meets regulatory requirements:
  • Implement privacy policy acceptance mechanism
  • Provide data access controls for user data
  • Implement data export functionality
  • Support data deletion (right to be forgotten)
  • Cookie consent management if using cookies
  • Log retention policies for security events
  • Comply with data protection regulations (GDPR, CCPA)
确保认证系统符合监管要求:
  • 实现隐私政策接受机制
  • 为用户数据提供访问控制
  • 实现数据导出功能
  • 支持数据删除(被遗忘权)
  • 若使用Cookie则需实现Cookie同意管理
  • 制定安全事件日志保留策略
  • 遵守数据保护法规(GDPR、CCPA)

Common Pitfalls to Avoid

需避免的常见陷阱

  • Never store passwords in plain text or reversible encryption
  • Don't expose user enumeration through different error messages
  • Avoid client-side only validation (always validate server-side)
  • Don't log sensitive data (passwords, tokens, personal information)
  • Never trust client-sent data without validation
  • Don't implement custom cryptography (use established libraries)
  • Avoid storing tokens in insecure locations
  • Don't skip rate limiting on authentication endpoints
  • Never expose stack traces or detailed errors to clients
Remember: Authentication is the foundation of application security. Implement it thoroughly, test it comprehensively, and maintain it diligently. A secure authentication system protects both users and the entire application.
  • 绝不要以明文或可逆加密方式存储密码
  • 不要通过不同的错误信息暴露用户枚举漏洞
  • 避免仅依赖客户端验证(始终在服务端验证)
  • 不要记录敏感数据(密码、令牌、个人信息)
  • 绝不要信任未经验证的客户端发送数据
  • 不要自行实现加密算法(使用成熟的库)
  • 避免在不安全的位置存储令牌
  • 不要跳过对认证端点的速率限制
  • 绝不要向客户端暴露堆栈跟踪或详细错误信息
请记住:认证是应用安全的基础。需全面实现、充分测试并持续维护。一个安全的认证系统既能保护用户,也能保护整个应用。