How to Pass Authorization Header from Swagger Doc in Python Fast API [duplicate]
Asked Answered
O

2

14

I am trying to pass authorization header using Documentation page, similar to this page:

enter image description here

Since, the documentations are automatic generated in Fast API, I am having hard time trying to figure this out. I followed this page https://fastapi.tiangolo.com/tutorial/security/ but couldn't find any info about passing the bearer token. Please note, I am not looking for validating the token, I am just looking for a way to pass bearer token through documentation page.

Can anyone please refer to some relevant documentation or with help.

Offload answered 31/1, 2022 at 12:51 Comment(3)
You can get it from the header. request.headersYawata
Did you try to declare header params in API and then checked the swagger. fastapi.tiangolo.com/tutorial/header-paramsVenus
Authorization header isn't allowed to be declared that way as per OpenAPI specs.Fruin
N
9

Authorization header cannot be asked by using Header().

You need a SecurityBase based Depends like HTTPBearer to tell swagger your api endpoint needs an Authorization header.

from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

auth_scheme = HTTPBearer()
@app.get("/me")
async def echo_me(token: HTTPAuthorizationCredentials = Depends(auth_scheme))
    ...

You can write a class inherits HTTPBearer or other security class if you want the credential be optional.

from fastapi import Depends, HTTPException, Request

class OptionalHTTPBearer(HTTPBearer):
    async def __call__(self, request: Request) -> Optional[str]:
        from fastapi import status
        try:
            r = await super().__call__(request)
            token = r.credentials
        except HTTPException as ex:
            assert ex.status_code == status.HTTP_403_FORBIDDEN, ex
            token = None
        return token

auth_scheme = OptionalHTTPBearer()
@app.get("/test")
async def test(token = Depends(auth_scheme)):
    return dict(token=token)
Nolpros answered 28/4, 2022 at 18:17 Comment(0)
A
7

For those who are here failing to understand why Swagger in FastAPI doesn't show their Security methods in the "Authorize" modal dialog, please bear in mind that due to this line each of the security definitions attached to your routes via dependency is registered under its class name by default unless you explicitly specify the scheme_name when instantiating the relevant Security class. The natural consequence of this is that if you have multiple similar Security classes used in your routes (eg. several APIKeyHeader()s) only last of them gets registered in the openAPI scheme definition (ie. catched by Swagger). So, the right way to use multiple Securities of the same kind is to specify the scheme_name explicitly:

auth_header1 = APIKeyHeader(name='X-SECRET-1', scheme_name='secret-header-1')
auth_header2 = APIKeyHeader(name='X-SECRET-2', scheme_name='secret-header-2')


@app.get("/test")
async def test(header_value1=Security(auth_header)):
    return dict(token=token)
Almira answered 26/7, 2022 at 18:9 Comment(1)
I've give up on that already, you made my day! thank you very much, I haven't found anything like at that in the docsDeli

© 2022 - 2024 — McMap. All rights reserved.