尝试从此 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
?
我对整个授权流程还很陌生,这个存储库足够简单,足以让我获得必要的部分。因此,如果您的回答坚持相同的项目结构,只回答如何在函数内部获取代币值的问题,而不引入太多新概念或不同的库等,我将不胜感激。
我的技术堆栈(如果重要的话)是
@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 的