FastAPI 怎样用 JWT 验证访问令牌?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
先从 Authorization 读取 Bearer 凭据,再用可信密钥和固定算法校验签名,并按系统要求核对过期、签发者与受众。之后加载用户,执行资源授权。
讲清原理
JWT 常以签名形态使用,内容可读。不要把解码后的字段直接当身份,也不要把令牌写进日志。过期与撤销策略应由系统设计。
例子与易错点
示例对本地测试令牌分别核对有效、缺少和受众不匹配的三条请求。验签与权限是两道条件。
from datetime import datetime, timedelta, timezone
from secrets import token_bytes
from typing import Annotated
import jwt
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from fastapi.testclient import TestClient
secret = token_bytes(32)
bearer = HTTPBearer(auto_error=False)
app = FastAPI()
def current_subject(auth: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)]):
unauthorized = HTTPException(401, "valid token required", {"WWW-Authenticate": "Bearer"})
if auth is None:
raise unauthorized
try:
claims = jwt.decode(auth.credentials, secret, algorithms=["HS256"],
issuer="https://issuer.example.org", audience="catalog",
options={"require": ["sub", "iss", "aud", "exp"]})
except jwt.InvalidTokenError:
raise unauthorized from None
return claims["sub"]
@app.get("/me")
def me(subject: Annotated[str, Depends(current_subject)]):
return {"sub": subject}
def fixture_token(audience):
return jwt.encode({"iss": "https://issuer.example.org", "aud": audience,
"sub": "reader", "exp": datetime.now(timezone.utc) + timedelta(minutes=5)},
secret, algorithm="HS256")
with TestClient(app) as client:
assert client.get("/me").status_code == 401
wrong = client.get("/me", headers={"Authorization": "Bearer " + fixture_token("other")})
assert wrong.status_code == 401 and wrong.headers["WWW-Authenticate"] == "Bearer"
valid = client.get("/me", headers={"Authorization": "Bearer " + fixture_token("catalog")})
assert valid.json() == {"sub": "reader"}
print("missing and wrong audience rejected; catalog accepted")
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。