Validating Users
NotesStill working with APIs, let’s add a new API that will use OAuth2PasswordRequestForm to validate a user using a clear text password. This is a standard login form, with username and password fields, which Swagger knows how to display.
It’s worth noting that python-multipart is needed to work with forms, which fastapi[standard] includes.
This process will prove that user authentication works, by first searching the database for a user account that matches an email address, then hashing the password entered by the user and comparing it with the hash stored in the user record found.
Add a function that takes in the clear text password and the hash of the password. password_hash.verify returns True if they match or False if they do not:
def verify_password_api(plain_password: str, hashed_password: str) -> bool:
return password_hash.verify(plain_password, hashed_password)Add another function that takes in a username and a clear text password. The function first queries the database to see if the user exists, then using the verify_password_api function, verifies the password:
password_hash = PasswordHash.recommended()
DUMMY_HASH = password_hash.hash("dummypassword") # NEWdef authenticate_user_api(username: str, password: str, session: Session) -> User | None:
query = select(User).where(User.username == username)
user = session.exec(query).first()
if not user:
# Check against a dummy hash anyway, so the response takes the same time
# whether or not the user exists (otherwise timing reveals valid usernames)
verify_password_api(password, DUMMY_HASH)
return None
if not verify_password_api(password, user.hashed_password):
return None
return userHashing a password with Argon2 is deliberately slow, which is what makes guessing passwords expensive. But it means that, without the dummy check, a login for an email address that doesn’t exist would return noticeably faster than one that does, and an attacker could use that to find out which email addresses have accounts. This is the approach used in the FastAPI documentation.
Add a new API validate_user_with_password_api that utilises the authenticate_user_api function. You’ll soon see that by using OAuth2PasswordRequestForm for this route, Swagger will provide login form functionality for us. Import Annotated and OAuth2PasswordRequestForm:
from typing import Annotated # NEW
from fastapi.security import OAuth2PasswordRequestForm # NEW@router.post('/auth/validate')
def validate_user_with_password_api(form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
session: Session = Depends(get_session_db)):
user = authenticate_user_api(form_data.username, form_data.password, session)
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password")
return {"detail": "User validated"}Annotated[OAuth2PasswordRequestForm, Depends()] tells FastAPI to build an OAuth2PasswordRequestForm from the submitted form fields. It’s the style the FastAPI documentation now prefers, and means the same as form_data: OAuth2PasswordRequestForm = Depends().
Run the application and go to http://localhost:8000/docs again, you can now test validating a user:
If you provide the correct credentials, you should expect a response:
{
"detail": "User validated"
}If you provide either an unknown email address or an incorrect password, you should expect a 401 Unauthorized response of:
{
"detail": "Incorrect username or password"
}The message is deliberately the same in both cases, so it doesn’t reveal whether the email address has an account.
Great, we can add users and have proved that user credentials can be validated. Next, we need to evolve this to generate a JWT token.