如何获取在 FastAPI 中作为依赖项传递的 HTTPBearer 令牌的值?

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

尝试从此 github 存储库学习使用 java-web-tokens 授权的基础知识。在这里复制相关部分以方便参考(我的评论)。

@app.post("/posts", dependencies=[Depends(JWTBearer())], tags=["posts"])
def add_post(post: PostSchema):
    # How to access the token string here? 
    # token:str=JWTBearer() # Will this help?
    # I want something like this
    # print(f'The supplied token is {token}.')
    post.id = len(posts) + 1
    posts.append(post.dict())
    return {
        "data": "post added."
    }

作者正在使用

JWTBearer
子类通过 JWT 授权特定路由。但是有没有一种简单的方法可以将令牌的值作为处理函数内的局部变量来访问
add_post

我对整个授权流程还很陌生,这个存储库足够简单,足以让我获得必要的部分。因此,如果您的回答坚持相同的项目结构,只回答如何在函数内部获取代币值的问题,而不引入太多新概念或不同的库等,我将不胜感激。

我的技术堆栈(如果重要的话)是

    fastapi 0.103.1
  • Python 3.10
  • Ubuntu 22.04
python jwt backend fastapi bearer-token
1个回答
0
投票
正如 Daviid 所提到的,您可以将依赖项从装饰器移至函数。

@app.post("/posts", tags=["posts"]) def add_post(post: PostSchema, token: Annotated[str, Depends(JWTBearer())]): # How to access the token string here? # token:str=JWTBearer() # Will this help? # I want something like this print(f'The supplied token is {token}.') post.id = len(posts) + 1 posts.append(post.dict()) return { "data": "post added." }
您可以参考FastAPI的

文档中的示例。

当您不需要依赖项的返回值时,使用路径操作装饰器中的依赖项 - FastAPI 的

文档

© www.soinside.com 2019 - 2024. All rights reserved.