gpt4 book ai didi

python - 在 python-fastApi 中间件中引发异常

转载 作者:行者123 更新时间:2023-12-04 11:50:34 25 4
gpt4 key购买 nike

我正在尝试在 fastapi 中间件中验证 token ,但这似乎是不可能的。因为我认为中间件需要进行下一次调用,尽管它不是必需的。我无法在这个 python-fastapi 后端找到任何好的解决方案来一次性处理 token 。任何帮助表示赞赏。

@app.middleware("http")
async def add_middleware_here(request: Request, call_next):
token = request.headers["Authorization"]
try:
verification_of_token = verify_token(token)
if verification_of_token:
response = await call_next(request)
return response
except InvalidSignatureError as er:
raise HTTPException(status_code=401)

最佳答案

您需要返回响应。我会告诉你如何让它工作:

from fastapi.responses import JSONResponse

@app.middleware("http")
async def add_middleware_here(request: Request, call_next):
token = request.headers["Authorization"]
try:
verification_of_token = verify_token(token)
if verification_of_token:
response = await call_next(request)
return response
else:
return JSONResponse(status_code=403) # or 401
except InvalidSignatureError as er:
return JSONResponse(status_code=401)

请注意,使用此中间件意味着您的 API 上没有登录路由(用于生成 token )。

此外,您应该考虑使用此依赖项: https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/

另一件事是您可以使用 fastapi.status为您的状态代码。

关于python - 在 python-fastApi 中间件中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61358669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com