Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python enable FastAPI API Key header

I want to enable API Key header to generate a Bearer token in my API using FastAPI, but I'm having troubles getting and sending Bearer token from the OpenAPI UI, my token endpoint looks like this

api_key_header = APIKeyHeader(name='X-API-Key', auto_error=True)

app_auth = APIRouter()


@app_auth.post('/token', summary="Returns Bearer Token",
               tags=["Auth"])
async def login(api_key_header: str = Security(api_key_header)):
    if api_key_header != '123':
        raise HTTPException(status_code=HTTP_401_UNAUTHORIZED,
                            detail='wrong api key',
                            headers={"WWW-Authenticate": "Bearer"})
    else:
        jwt_token = create_jwt_token(user)
        return jwt_token

This works and returns the bearer token as expected enter image description here

It also shows me the header from the Authorize buttom enter image description here enter image description here

But then I have troubles by passing this generated token to another endpoint through OpenAPI (it works if I just send it in headers with other client), when I test other endpoint, its not sending the token in headers enter image description here

I also have enabled

oauth_schema = OAuth2PasswordBearer(tokenUrl='/token')
app = FastAPI(title="My test api", version="1.0")

app.include_router(app_auth)
app.include_router(app_test, prefix='/v1.0', dependencies=[Depends(check_jwt_token)])

and check_jwt_token

async def check_jwt_token(token: str = Depends(oauth_schema)):
   """
   it decods the token and check if already expired
   """

extra: you can see the endpoint handles correctly the Bearer token, testing from postman

enter image description here

like image 320
Rodrigo A Avatar asked Nov 15 '25 17:11

Rodrigo A


1 Answers

I just figure it out, here is the answer in case it helps someone else

I just had to change the oauth_schema = OAuth2PasswordBearer(tokenUrl='/token')

for oauth_schema = HTTPBearer() and change async def check_jwt_token(token: HTTPAuthorizationCredentials = Security(oauth_schema)) , and inside the function:

token= token.dict()['credentials']

like image 124
Rodrigo A Avatar answered Nov 18 '25 07:11

Rodrigo A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!