MushroomMaula / fastapi_login

FastAPI-Login tries to provide similar functionality as Flask-Login does.
https://pypi.org/project/fastapi-login
MIT License
639 stars 58 forks source link

Returns Invalid Credentials every time #90

Closed max-programming closed 2 years ago

max-programming commented 2 years ago

I am new to FastAPI and Python and I really like using this library. But for some reason it throws the invalid credentials error every time I try to request a protected route.

The thing is, I can log in successfully, I also get the token. But when I use that token as a bearer token in the header or use the FastAPI interface to send a request, it behaves the same.

image

I guess I might have done something wrong. This is my code.

Also the query_user function is marked async because I prev used my database to get the user but even when I tried it with dummy user, it still behaves the same.

from fastapi import Depends, FastAPI
from fastapi.requests import Request
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_login import LoginManager
from fastapi_login.exceptions import InvalidCredentialsException
from passlib.hash import bcrypt

DB = {
    "users": {
        "johndoe@mail.com": {
            "name": "John Doe",
            "password": "hunter2",
        }
    }
}
SECRET = "my-secret"

app = FastAPI()
manager = LoginManager(SECRET, token_url="/login")

@manager.user_loader()
async def query_user(username: str):
    return DB["users"].get(username)

@app.get("/protected")
def protected_route(user=Depends(manager)):
    return {"user": user}

@app.post("/login")
async def login(data: OAuth2PasswordRequestForm = Depends()):
    username = data.username
    password = data.password

    user = await query_user(username)

    if user is None:
        raise InvalidCredentialsException
    # elif not bcrypt.verify(password, user.password):
    elif password != user["password"]:
        raise InvalidCredentialsException

    access_token = manager.create_access_token(data={"username": username})
    return {"access_token": access_token, "token_type": "bearer"}
MushroomMaula commented 2 years ago

Instead of returning the username in the username field of your token try using sub. Also have a look here. When authenticating, i.e. reading and parsing the token, fastapi-login looks for the user identifier under the sub (=subject) field, as this part of the official jwt rfc.

max-programming commented 2 years ago

Works flawlessly! Thanks!