Vlad Vlad
Vlad Vlad

Reputation: 170

get_current_user doesn't work (OAuth2PasswordBearer problems)

This is actually the first time it doesn't work, I mean I've practiced this before, but now I have no idea what's wrong.

So I am trying to implement basic function get_current_user for FastAPI, but somehow it doesn't work.

When I try in swagger Authorization works fine, but endpoint with current user simply doesn't work.

So this is part that belongs to endpoint file:

router = APIRouter(prefix='/api/v1/users')
router1 = APIRouter()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/api-token-auth/')


@router1.post('/api-token-auth/')
async def auth(form: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = await utils.get_user_by_username(form.username, db)  # type: User
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    if not utils.validate_password(form.password, user.hashed_password):
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    return await utils.create_token(user.id, db)


async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    print(token)
    user = await utils.get_user_by_token(token, db)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )

    return user


@router.get("/me", response_model=DisplayUser)
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user

and this is function that creates token (I have checked and it is 1000% works and returns string):

async def create_token(user_id: int, db: Session):
    """Token generation"""
    letters = string.ascii_lowercase
    token = ''.join(random.choice(letters) for _ in range(25))
    created_token = Token(
        expires=datetime.now() + timedelta(weeks=2),
        user_id=user_id,
        token=token
    )
    db.add(created_token)
    db.commit()
    db.refresh(created_token)
    token = AuthUser.from_orm(created_token)
    return token.token

But when I print(token) in get_current_user function it prints undefined. And I dunno why. Am I using dependency wrong or something?

Thanks in advance!

Upvotes: 2

Views: 2015

Answers (2)

MJG
MJG

Reputation: 11

In your "create_token(user.id, db)" ensure the returned token contains these two values. { "access_token":"", "token_type":"bearer" }

Upvotes: 0

MatsLindh
MatsLindh

Reputation: 52832

Since it prints undefined it seems like the frontend is expecting the response in a different format (since undefined is what using an undefined object key in Javascript as a key will result in).

The OAuth2 response should have the token under access_token by default:

access_token (required) The access token string as issued by the authorization server.

token_type (required) The type of token this is, typically just the string “bearer”.

Example response from the above link:

{
  "access_token":"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3",
  "token_type":"bearer",
  "expires_in":3600,
  "refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk",
  "scope":"create"
}

Upvotes: 1

Related Questions