Nice!
You can simplify a bit some pieces with:
from fastapi.security.http import HTTPBearer, HTTPBasicCredentials
And then:
auth = HTTPBearer()
@app.post(“/test”)
async def test(authorization: HTTPBasicCredentials = Depends(auth)):
…
HTTPBearer will automatically return an error if there's no bearer token, and the HTTPBasicCredentials object will contain the extracted token (trimming the "bearer").
This is not properly documented yet :/. But the parts are already available: https://github.com/tiangolo/fastapi/blob/master/fastapi/security/http.py#L92
And you can also create a dependency that uses that authorization, and extracts and returns the current user.
That way your path operation/routes code can just include the dependency to get the current user, and that will, in turn, depend on the extraction and verification of the token. So, if you create a dependency: valid_current_user, you could use it like:
@app.post(“/test”)
async def test(user: str = Depends(valid_current_user)):
return {“message”: f”Hello {user}”}
Here's an example of that: https://fastapi.tiangolo.com/tutorial/security/get-current-user/#get-the-user
Sorry for the lack of formatting, Medium doesn't let me paste in a code-formatted block :/