Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

FastAPI 怎样实现基于角色的访问控制?

查看完整题解

参考回答

直接回答

用依赖先获得可靠的当前用户,再检查其角色或权限集合。路由可明确要求编辑权。拒绝时根据认证与授权结果返回合适状态。

讲清原理

角色仅代表一部分规则。即使用户是编辑者,也只能操作授权项目。敏感权限变化不能全靠一份很久不更新的令牌。

例子与易错点

示例使用明确的测试身份,验证编辑者可进入,而只读角色得到 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")

相关题:第 61 题、第 62 题、第 71 题、第 72 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。