Trying to learn the basics of authorisation using java-web-tokens from this github repository. Reproducing the relevant part here for easy reference (comments mine).
@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."
}
The author is using the JWTBearer
subclass to authorise the specific route with a JWT. But is there a simple way to access the value of the token as a local variable inside the handler function add_post
?
I am pretty new to the whole authorisation-flow, and this repository is simple enough for me to get the essential parts. So I would appreciate if you answer sticks to the same project structure, just answering the question on how to get the token value inside the function, without introducing too many new concepts, or a different library etc.
My technology stack (if important) is
As mentioned by Daviid, you can move the dependencies from the decorator to the function.
@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."
}
You can refer to the example in FastAPI's documentation.
Dependencies in path operation decorators are used when you don't need the return value of a dependency - FastAPI's documentation