Search code examples
pythonfastapihttp-authentication

Remove credential from cookies in fast api


I have a fast api app. I would like to set up a basic HTTP auth like this (I know it is not safe but this is for test purposes):

users = {
    "poisson": "rouge",
    "alice": "nevers",
    "bob": "dylan"
}

def user_login(credentials: HTTPBasicCredentials = Depends(security)):
    if not (credentials.username in users.keys() and users[credentials.username] == credentials.password):
        raise HTTPException(
            status_code = status.HTTP_401_UNAUTHORIZED,
            detail="Mauvais username ou mot de passe",
            headers={"WWW-Authenticate": "Basic"}
        )
    return credentials.username


@app.get("/somewhere")
def my_func(credentials: HTTPBasicCredentials = Depends(user_login), n: int = 20):
    # do something
return json

My frist question is, how can I "tell" to not store credentials in cookies ? Because as I am doing a lot of tests, as soon as i log in even if i use the logoutin fastapi swager i still have the credentials (I need to remove cookies from chrome setup).

My second question is, how can I return also the credentials.username in my function my_func as i am already returning a json with different data. Should i insert credentials data into my json ?


Solution

  • There is nothing in your code that indicates that a cookie is being used. The swagger UI might use a cookie to store the authentication information to avoid having to retype it for each request, but your own API does not seem to use cookies in any way.

    For programmatic testing I suggest using TestClient instead.

    When returning the data, you'll have to decide what makes sense, you can for example return two levels of data in a dictionary:

    return {'username': credentials, 'func_result': json}