auth-patternslisted
Install: claude install-skill afine907/skills
# Auth Patterns — 认证授权模式
实现安全的认证授权系统,支持多种认证方式和权限模型。
## Goal
实现认证授权模式,包含 JWT、OAuth2、Session、RBAC/ABAC 权限模型、多因素认证
## Trigger
- 用户要求"实现登录"、"JWT认证"、"OAuth2"
- 需要设计权限系统
- 需要实现多因素认证
## 认证方式对比
| 方式 | 适用场景 | 优势 | 劣势 |
|------|----------|------|------|
| JWT | 前后端分离、微服务 | 无状态、可扩展 | 无法即时撤销 |
| Session | 传统 Web 应用 | 可控、可撤销 | 需要存储、跨域复杂 |
| OAuth2 | 第三方登录 | 标准化、安全 | 实现复杂 |
| API Key | 服务间调用 | 简单 | 功能有限 |
## JWT 认证实现
### Token 结构
```python
# Access Token (短期,15分钟)
{
"sub": "user_id",
"email": "user@example.com",
"role": "admin",
"permissions": ["read:users", "write:users"],
"iat": 1704067200,
"exp": 1704068100,
"jti": "unique_token_id"
}
# Refresh Token (长期,7天)
{
"sub": "user_id",
"type": "refresh",
"iat": 1704067200,
"exp": 1704672000,
"jti": "unique_token_id"
}
```
### Python 实现
```python
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
# 配置
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 15
REFRESH_TOKEN_EXPIRE_DAYS = 7
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
def create_access_token(data: dict, expires_delta: timedelta = None) -> str:
to_encode = data.copy()
expire = datetime.utc