How to get the user object when the user is logged in and None otherwise?

Question:

How to get the user object if the user is logged in and None otherwise?

Following the FastAPI documentation for getting the user the /api_limits endpoint below returns a 401 when the user is not logged in (in an application with proper jwt signatures).

from typing import Optional

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None


def fake_decode_token(token):
    return User(
        username=token + "fakedecoded", email="[email protected]", full_name="John Doe"
    )


async def get_current_user(token: str = Depends(oauth2_scheme)):
    user = fake_decode_token(token)
    return user


@app.get("/api_limits")
async def read_users_me(current_user: User = Depends(get_current_user)):
    if current_user is None:
        return 2
    return 5

How to get the current_user user object inside the /api_limits endpoint in the sample code above to be None when the user is not logged in?

Asked By: Greg

||

Answers:

The OAuth2PasswordBearer automagically generates a 401 error if no Authorization header is present at all (i.e. there is no valid token being submitted).

If you don’t want this to happen, you can set auto_error=False – in which case it will return None instead if no header is found. You can then change your get_current_user method to return None instead of a user if no token is present:

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)

...

async def get_current_user(token: str = Depends(oauth2_scheme)):
    if not token:
        return None

    user = fake_decode_token(token)
    return user    
Answered By: MatsLindh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.