Authorization header is not sent in request using FastAPI

Question:

In my code, I have a request header "Authorization", but in /docs, the header is not sent:

 @router.get('/versions',tags=["Credentials"],responses={
        200: {
            "model": List[models.versions_info],
            "description": "Return has code",
            "headers": {"Authorization": {"description":"Token party","type":"string"}}
        }})
async def list_versions(request: Request,token: Union[str, None] = Header(alias="Authorization",default=None)): 
    print(token)
    out=[{"version": "2.1.1","url": "https://www.server.com/ocpi/2.1.1/"},{"version": "2.2","url": "https://www.server.com/ocpi/2.2/"}]
    return Response(status_code=200,content=json.dumps(out), media_type="application/json", headers={"Authorization": "Token "+config.globals['mytoken']})

In Docs:

enter image description here

Asked By: Pavel Gribov

||

Answers:

You can not do it that way. Authorization is a reserved header here and you can not override it. if you rename it to something different you’ll see it in curl and it would work as expected. See here how you can implement jwt-based auth: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/

Or you can use Security functionality to archive it. This is a self-contained working example (creds to @Pavel Gribov):

from fastapi import Security, Depends, FastAPI
from fastapi.security.api_key import APIKeyHeader

from pydantic import BaseModel

app = FastAPI()

token_key = APIKeyHeader(name="Authorization")


class Token(BaseModel):
    token: str


def get_current_token(auth_key: str = Security(token_key)):
    return auth_key


@app.get("/get_items")
def read_items(current_token: Token = Depends(get_current_token)):
    return current_token

See how it works.

Answered By: funnydman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.