FastAPI从API密钥获取用户ID [英] FastAPI get user ID from API key
问题描述
在fastAPI中,您可以简单地在路由器级别编写安全性依赖性,并保护URL的整个部分.
In fastAPI one can simply write a security dependency at the router level and secure an entire part of the URLs.
router.include_router(
my_router,
prefix="/mypath",
dependencies=[Depends(auth.oauth2_scheme)]
)
这避免了重复很多代码.
This avoids repeating a lot of code.
唯一的问题是,我希望通过路由器级别的依赖关系来保护URL的一部分,该依赖关系会检查用户令牌的有效性并检索该令牌的用户ID.
The only problem is that I would like to protect a part of URLs with a router level dependency that checks the validity of the user token and retrieve the user id for that token.
我发现的唯一方法是向所有功能添加另一个依赖关系,但这导致重复刚才保存的代码.
The only way I found, is to add another dependency to all the functions, but this leads to repeating the code that I just saved.
长话短说,有没有一种方法可以在路由器级别添加依赖项,检索并返回用户ID,并将返回的值传递给处理函数?像
Long story short, is there a way to add the dependency at the router level, retrieve and return the user id, and pass the returned value to the handling function? Something like
router.py
router.include_router(
my_router,
prefix="/mypath",
dependencies=[user_id = Depends(auth.oauth2_scheme)]
)
my_router.py
my_router = APIRouter()
@my_router.get("/my_path")
async def get_my_path(**kwargs):
user_id = kwargs["user_id"]
# Do stuff with the user_id
return {}
推荐答案
在依赖关系函数中对用户进行身份验证后,将user_id添加到 request.state
,然后在您的路线上就可以从请求对象.
Once the user is authenticated in the dependency function add the user_id to request.state
, then on your route you can access it from the request object.
async def oauth2_scheme(request: Request):
request.state.user_id = "foo"
my_router = APIRouter()
@my_router .get("/")
async def hello(request: Request):
print(request.state.user_id)
app.include_router(
my_router,
dependencies=[Depends(oauth2_scheme)]
)
这篇关于FastAPI从API密钥获取用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!