Hashing passwords via FastAPI
The FastAPI documentation already has a good article on this topic: Click here!
First thing we have to do is install
passlibto usebcrypt
pip install passlib[bcrypt]
# If the above does not work use:
pip install passlib
pip install bcryptWe will have to import the
CryptContextand tellpasslibwhat is the default hashing algorithm
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")We also have to update the operation path
@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=schemas.UserOut)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db), ):
# Hash the Password - user.password
hashed_password = pwd_context.hash(user.password)
user.password = hashed_password
new_user = models.User(**user.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_userBefore creating the user, we are getting the password hashed via
pwd_context.hashAfter which we are replacing
user.passwordin the schema with the hashed passwordAs this is updated it should store the hashed password in the database
A better approach would be to create an additional file where we would store useful code
We will call this file
utils.pyIn this file we can import all the logic and define a function to hash our password
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash(password: str):
return pwd_context.hash(password)The thing that changes in our
main.pyfile is the import and the variable passed in the operation path
from . import models, schemas, utils
@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=schemas.UserOut)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db), ):
# Hash the Password - user.password
hashed_password = utils.hash(user.password) # Here
user.password = hashed_password
new_user = models.User(**user.dict())
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_userLast updated