在 FastAPI 中,您可以使用DependsHTTPBearer来获取请求中的 Bearer Token 值。以下是一个示例:\n\npython\nfrom fastapi import Depends, FastAPI, HTTPException\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\n\napp = FastAPI()\nsecurity = HTTPBearer()\n\n# 定义一个依赖项函数,用于验证和提取Bearer Token\nasync def get_token(credentials: HTTPAuthorizationCredentials = Depends(security)):\n if not credentials.scheme == "Bearer":\n raise HTTPException(status_code=401, detail="Invalid authentication scheme")\n return credentials.credentials\n\n# 使用依赖项函数来获取Bearer Token值\n@app.get("/protected_route")\nasync def protected_route(token: str = Depends(get_token)):\n return {"token": token}\n\n\n在上面的示例中,我们首先导入HTTPBearerHTTPAuthorizationCredentials类,然后创建一个HTTPBearer实例作为安全配置。然后,我们定义了一个名为get_token的依赖项函数,它使用Depends装饰器来将HTTPAuthorizationCredentials作为参数。在该函数中,我们首先检查Bearer Token的认证方案是否为"Bearer",如果不是,则返回401错误。最后,我们返回提取到的Bearer Token值。\n\n在protected_route路由处理程序中,我们使用Depends(get_token)来声明一个依赖项,它将调用get_token依赖项函数来获取Bearer Token值,并将其作为token参数传递给路由处理程序。\n\n这样,当请求到达/protected_route路由时,FastAPI将自动调用get_token依赖项函数来获取Bearer Token值,并将其作为参数传递给protected_route路由处理程序。

FastAPI 中获取 Bearer Token 的方法

原文地址: https://www.cveoy.top/t/topic/qd5f 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录