FastAPI访问令牌的权限声明与作用域管理:你的API安全真的无懈可击吗?
title: FastAPI访问令牌的权限声明与作用域管理:你的API安全真的无懈可击吗?


from pydantic import BaseModel
from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
# 配置OAuth2方案
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="token",
scopes={
"read": "查看数据权限",
"write": "修改数据权限",
"admin": "管理员权限"
}
)
# 用户模型
class User(BaseModel):
username: str
scopes: list[str] = []
# 权限验证依赖项
async def check_permissions(required_scope: str, token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, "SECRET_KEY", algorithms=["HS256"])
user_scopes = payload.get("scopes", [])
# 使用集合判断作用域包含关系
if required_scope not in user_scopes:
raise HTTPException(
status_code=403,
detail="权限不足"
)
return payload
except JWTError:
raise HTTPException(
status_code=401,
detail="无效凭证"
)
app = FastAPI()
@app.post("/token")
async def login():
# 实际项目应从数据库验证用户
return {
"access_token": jwt.encode(
{"scopes": ["read", "write"]},
"SECRET_KEY",
algorithm="HS256"
),
"token_type": "bearer"
}
@app.get("/users/me")
async def read_user_me(
current_user: dict = Depends(check_permissions("read"))
):
return {"user": current_user}
@app.post("/users")
async def create_user(
current_user: dict = Depends(check_permissions("write"))
):
return {"status": "用户创建成功"}
@app.delete("/users/{user_id}")
async def delete_user(
user_id: int,
current_user: dict = Depends(check_permissions("admin"))
):
return {"status": "用户已删除"}
答案解析 正确答案:B
read作用域允许访问/users/me端点,write作用域允许访问POST /users端点,但delete操作需要admin权限。
read作用域允许访问/users/me端点,write作用域允许访问POST /users端点,但delete操作需要admin权限。
答案解析 正确答案:B
401错误对应认证失败,403表示已认证但权限不足,当令牌缺失必要作用域时触发。
401错误对应认证失败,403表示已认证但权限不足,当令牌缺失必要作用域时触发。
{
"detail": [
{
"loc": [
"header",
"authorization"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
{
"detail": "Invalid authentication credentials"
}
# 建议的令牌生成配置
jwt.encode(
{
"sub": "user123",
"scopes": ["read"],
"exp": datetime.utcnow() + timedelta(minutes=30)
},
"YOUR_SECRET_KEY", # 推荐使用RSA256更安全
algorithm="HS256"
)
pip install fastapi==0.68.0
pip install pydantic==1.8.2
pip install python-jose==3.3.0
pip install uvicorn==0.15.0
评论
发表评论