Home > Blockchain >  fastapi set auth token basic
fastapi set auth token basic

Time:04-14

I'm trying to have a security API token for a basic API I'm setting up.

For some reason when using this setup, it isn't working, i.e.,

async def get_emotions(uid, substance, x_token: Optional[str] = Header(None)):
    if x_token != os.getenv('APIKEY'):
        raise HTTPException(status_code=401,
                            detail='wrong api key',
                            headers={"WWW-Authenticate": "Bearer"})

Using a query like this,

curl --location --request GET 'http://0.0.0.0:8008/Emotions.json?uid=xxxx&substance=Dexamphetamine' \
--header 'x_token: example$oken'

Is returning an error of 401 not authenticated, even though my environment variables are picking up the same token.

Any idea on solving this issue?

CodePudding user response:

You need to set convert_underscores to False in the Header(...)

Thus, your function will be as,

async def get_emotions(
    uid, substance, x_token: Optional[str] = Header(None, convert_underscores=False)
):
    if x_token != os.getenv("APIKEY"):
        raise HTTPException(
            status_code=401,
            detail="wrong api key",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return {"foo": "bar"}
  • Related