Reputation: 661
I am trying to pass authorization header using Documentation page, similar to this page:
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.
Upvotes: 16
Views: 27677
Reputation: 1082
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)
Upvotes: 9
Reputation: 1457
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)
Upvotes: 7