扫描二维码
关注或者微信搜一搜:编程智域 前端至全栈交流与成长
发现1000+提升效率与开发的AI工具和实用程序:https://tools.cmdragon.cn/
通过三层防护体系实现API安全:
# 安装依赖:pip install python-jose[cryptography]==3.3.0 passlib==1.7.4
from jose import JWTError, jwt
from datetime import datetime, timedelta
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=401,
detail="无法验证凭证",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
return username
graph TD A[用户] -->|登录| B(认证服务器) B -->|授权码| A A -->|提交授权码| C[客户端] C -->|换取令牌| B B -->|访问令牌| C C -->|访问资源| D[资源服务器]
# 配置示例:pip install authlib==1.0.1
from fastapi.security import OAuth2AuthorizationCodeBearer
oauth2_scheme = OAuth2AuthorizationCodeBearer(
authorizationUrl='https://provider.com/auth',
tokenUrl='https://provider.com/token',
scopes={"read": "读取权限", "write": "写入权限"}
)
@app.get("/login/google")
async def login_google():
return RedirectResponse(
url=(
"https://accounts.google.com/o/oauth2/auth"
"?response_type=code"
"&client_id=your-client-id"
"&redirect_uri=http://localhost:8000/callback"
"&scope=openid%20profile%20email"
)
)
flowchart TB A[信息收集] --> B[漏洞扫描] B --> C{存在漏洞?} C -->|是| D[渗透攻击] C -->|否| E[生成报告] D --> F[权限提升] F --> G[数据窃取] G --> E
# 使用SQLAlchemy防止注入(pip install sqlalchemy==1.4.46)
from sqlalchemy import text
@app.get("/items/")
async def read_items(name: str):
# 错误写法:f"SELECT * FROM items WHERE name = '{name}'"
query = text("SELECT * FROM items WHERE name = :name")
result = await database.execute(query, {"name": name})
return result.fetchall()
问题:JWT 令牌应该存储在客户端的哪个位置最安全?
答案:C。HTTPOnly Cookie 可以防止XSS攻击窃取令牌,配合Secure和SameSite属性使用更安全。
问题:当收到401 Unauthorized响应时,首先应该检查:
答案:B。令牌过期是最常见的401错误原因,需检查令牌生成时间和有效期设置。
错误现象:422 Validation Error
{
"detail": [
{
"loc": [
"body",
"password"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
解决方案:
class UserCreate(BaseModel):
username: str = Field(min_length=3)
password: str = Field(min_length=8, regex="^(?=.*[A-Za-z])(?=.*d).{8,}$")
余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长
,阅读完整的文章:如何在FastAPI中玩转JWT认证与OAuth2集成,同时确保安全无虞?
参与评论
手机查看
返回顶部