FASTAPI - 尝试制作一个可用于所有端点的通用 token_verifyer

问题描述 投票:0回答:1

async def get_verified_token(request: Request):
    headers = request.headers
    token = headers.get('authorization')
    if not token:
        raise HTTPException(status_code=401, detail="Authorization token is missing")
    try:
        user = auth.verify_id_token(token)
    except auth.InvalidIdTokenError:
        raise HTTPException(status_code=401, detail="Invalid ID token")
    except auth.RevokedIdTokenError:
        raise HTTPException(status_code=401, detail="Revoked ID token")
    except Exception:
        raise HTTPException(status_code=500, detail="Internal server error")
    return user
    
# Define the endpoint to validate the token
@authRouter.post("/get_user_with_token")
async def validate(request:Request,user = Depends(get_verified_token)):
    """ Use this endpoint to verify the token and get the user details """
    return JSONResponse(content={"user":user}, status_code=200)

目前,我正在 FASTAPI 中执行上述操作,以在有人点击

/get_user_with_token
端点时验证令牌 - 来自 firebase 的令牌得到验证并返回用户

我想使这个通用,以便它适用于我将来添加的任何路线,即使是那些没有请求对象的路线(如果可能的话)

@authRouter.get("/get_data")
async def get_data(getGoalsData: GetGoalsData, current_user = Depends(get_verified_token)):
    # Your protected endpoint logic here
    return {"message": "This is protected data"}

如果我有像上面这样的路由,我希望 current_user 与经过验证的令牌一起存储。 (在这种情况下我没有

reqeuest:Request

这可以做到吗?如果可以的话我该怎么办?

python python-3.x firebase fastapi python-decorators
1个回答
0
投票

你应该使用Fastapi中间件

在你的情况下,它看起来像这样:

import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def add_proceverify_token(request: Request, call_next):
    user = await get_verified_token(request)
    response = await call_next(request)
    return response
© www.soinside.com 2019 - 2024. All rights reserved.