FastAPI 怎样实现基于角色的访问控制?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
用依赖先获得可靠的当前用户,再检查其角色或权限集合。路由可明确要求编辑权。拒绝时根据认证与授权结果返回合适状态。
讲清原理
角色仅代表一部分规则。即使用户是编辑者,也只能操作授权项目。敏感权限变化不能全靠一份很久不更新的令牌。
例子与易错点
示例使用明确的测试身份,验证编辑者可进入,而只读角色得到 403。真实身份应来自验证过的凭据。
from dataclasses import dataclass
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
@dataclass(frozen=True)
class Identity:
role: str
app = FastAPI()
def current_identity() -> Identity:
# The test replaces this boundary; a real service verifies credentials here.
raise HTTPException(401, "not authenticated", {"WWW-Authenticate": "Bearer"})
def must_edit(identity: Annotated[Identity, Depends(current_identity)]):
if identity.role != "editor":
raise HTTPException(403, "edit permission required")
@app.post("/drafts", dependencies=[Depends(must_edit)], status_code=201)
def create_draft():
return {"id": "draft-1"}
with TestClient(app) as client:
assert client.post("/drafts").status_code == 401
app.dependency_overrides[current_identity] = lambda: Identity("reader")
try:
assert client.post("/drafts").status_code == 403
app.dependency_overrides[current_identity] = lambda: Identity("editor")
assert client.post("/drafts").status_code == 201
finally:
app.dependency_overrides.pop(current_identity)
print("anonymous 401; reader 403; editor 201")
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。