如何为签名验证失败返回 401 并隐藏内部错误详情?
解读
国内生产环境对“安全透出”要求极高:
- 任何验签失败只能返回 401 Unauthorized,不能带堆栈、密钥 ID、算法名等敏感信息;
- 需要与 FastAPI 的自动文档、依赖注入、异常处理器无缝整合,保证业务代码零侵入;
- 面试官常追问“如何防止时序攻击”“如何兼容 Swagger”“如何单元测试”,回答必须闭环。
知识点
- HTTPException(status_code=401, headers={"WWW-Authenticate": "Bearer"})
- 自定义异常处理器 app.add_exception_handler
- 依赖项(Depends)里 raise HTTPException,FastAPI 会拦截并走统一处理器
- 日志双写:面向开发打印详细 traceback,面向用户只打印 request_id
- 时序攻击防护:使用 hmac.compare_digest 而不是 ==
- OpenAPI 排除内部头:在 response_model_exclude 或 schema_extra 里抹掉 detail 字段
答案
# main.py
import logging
import hmac
import os
from typing import Optional
from fastapi import FastAPI, Depends, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
logger = logging.getLogger("uvicorn.error")
app = FastAPI(title="签名演示服务", version="1.0.0")
# 1. 自定义异常,方便统一处理
class SignatureError(HTTPException):
def __init__(self) -> None:
super().__init__(status_code=401, headers={"WWW-Authenticate": "Bearer"})
# 2. 全局异常处理器:对外只返回固定文案,对内写日志
@app.exception_handler(SignatureError)
async def signature_error_handler(request: Request, exc: SignatureError) -> JSONResponse:
# 生产环境可替换为 request_id 或 trace_id
logger.warning("签名验证失败 %s", request.url.path)
return JSONResponse(
status_code=401,
content={"code": 401, "msg": "Unauthorized"},
headers={"WWW-Authenticate": "Bearer"},
)
# 3. 依赖:验签逻辑
SECRET = os.getenv("SIGN_SECRET", "super-secret").encode()
def verify_signature(credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer())) -> None:
"""
简单示例:把 Authorization: Bearer <signature> 与 body 做 HMAC-SHA256 比对
实际项目可换成微信/支付宝/自研算法
"""
# 这里仅演示,真实场景需读取 await request.body()
expected = hmac.new(SECRET, b"request-body", "sha256").hexdigest()
if not hmac.compare_digest(credentials.credentials, expected):
raise SignatureError()
# 4. 业务接口
@app.post("/webhook", dependencies=[Depends(verify_signature)])
async def webhook():
return {"status": "ok"}
运行效果:
- 签名正确 → 200 {"status": "ok"}
- 签名错误 → 401 {"code": 401, "msg": "Unauthorized"},响应头带 WWW-Authenticate,日志里打印路径但无堆栈
拓展思考
- 时序攻击:务必用 hmac.compare_digest,禁止用 ==;
- 重放攻击:在签名串里加入 timestamp 与 nonce,依赖项里校验有效期(如 60 s),失败同样抛 SignatureError;
- Swagger 调试:/docs 默认不带签名头,可写另一个依赖 allow_dev_skip,检测到 ENV == "dev" 时直接返回,方便联调;
- 多密钥轮换:把 SECRET 放到 Redis 或配置中心,支持按 key-id 路由不同密钥,验签失败不提示“key not found”;
- 单元测试:用 TestClient 传入错误签名,断言 resp.status_code == 401 且 json() 不含 detail;
- 审计合规:记录 user_ip、ua、request_id,日志脱敏后上报 ELK,满足等保 2.0 对“失败认证事件”审计要求。