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
)
这能做到吗?如果是这样,我该怎么做?
1条答案
按热度按时间ttcibm8c1#
您应该使用Fastapi middleware
在你的例子中,它看起来像这样: