python - 在 Fastapi 中,在哪里放置用于身份验证的依赖项/依赖项?

标签 python python-3.x authentication fastapi

我在 Fastapi 身份验证中看到了两种不同的使用方法:
方法一:

@app.get('/api/user/me')
async def user_me(user: dict = Depends(auth)):
    return user
和方法2:
@app.get('/api/user/me', dependencies=[Depends(auth)])
async def user_me(user: dict):
    return user
方法 1 和方法 2 之间有什么区别,哪个更适合保护 API,即需要身份验证?

最佳答案

正如@Omer Alkin 正确指出的那样,当我们想要使用其返回值(用户或 token 或 smth.)时,需要在路径操作参数列表中指定依赖项。这是来自 documentation 的示例:

async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)
    return user


@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user
如果依赖的返回值对我们来说不重要或者不返回,但只有一个副作用是重要的,例如依赖抛出异常,那么我们可以在路径操作装饰器中指定依赖。
在这种情况下,我们还可以使用 APIRouter 立即为一组操作执行依赖项(进行身份验证)。 :

async def get_token_header(x_token: str = Header(...)):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")

router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)
还需要注意的是,您可以在路径操作或其子依赖中重用相同的依赖,因为 FastAPI 实现了 cache policy默认情况下:

If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request.

关于python - 在 Fastapi 中,在哪里放置用于身份验证的依赖项/依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67307265/

相关文章:

python - 为什么我不能在 Python 3.x 中使用 python-cjson?

python - python 中的自定义类 : does a method HAVE to be called with an instance?

python - 如何正确写出 Pandas 系列中的 TSV 文件?

python-3.x - Pyqt5 方法关闭或删除小部件并根据命令重新设置它

python-3.x - Matplotlib basemap 绘制县有问题

android - Google Identity Signin API 始终返回带有服务器客户端 ID 的 NULL

Python - 在分组后将行转换为列并为不匹配的行填充零

python - Djongo 无法使用 Django-rest-framework 正确获取对象数组嵌入字段

asp.net-core - ASP.NET Core 中的 SSO 实现

authentication - REST 服务的基于 Spring Security 的身份验证