Password Hashing with Passlib

Storing plain-text passwords in a database is a security risk. To protect user credentials, it’s essential to use strong password hashing algorithms. Passlib is a popular Python library that provides various password hashing algorithms and utilities. In this guide, we’ll demonstrate how to use Passlib to hash passwords in a FastAPI application.

Installing Passlib

Install Passlib using pip:

Bash

pip install passlib

Hashing Passwords

Use the hash function from Passlib to hash a password:

Python

from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_password(password: str):
    return pwd_context.hash(password)   

Verifying Passwords

Use the verify function to verify a password against a hashed password:

Python

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

Integrating with FastAPI

Modify your user registration endpoint to hash the password before storing it in the database:

Python

from app.utils import hash_password

@router.post("/register", response_model=UserSchema)
async def register_user(user: UserCreate, db: Session = Depends(get_db)):
    # ...
    hashed_password = hash_password(user.password)
    db_user = User(email=user.email, password=hashed_password)
    # ...

Testing Password Hashing

Write tests to ensure that passwords are hashed correctly and cannot be easily reversed:

Python

def test_hash_password(client):
    password = "password123"
    hashed_password = hash_password(password)
    assert hashed_password != password
    assert pwd_context.verify(password, hashed_password)
Generating Access Tokens
Adding Tests for the User Registration Endpoint

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?