Password hashing with bcrypt helps keep user passwords safe by turning them into secret codes that are hard to guess or steal.
0
0
Password hashing with bcrypt in FastAPI
Introduction
When you want to store user passwords securely in a database.
When building a login system that checks passwords safely.
When you want to protect user accounts from hackers.
When you need to verify a password without saving it in plain text.
Syntax
FastAPI
from passlib.context import CryptContext pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") # To hash a password hashed_password = pwd_context.hash("mysecretpassword") # To verify a password is_valid = pwd_context.verify("mysecretpassword", hashed_password)
Use hash() to create a hashed password from plain text.
Use verify() to check if a plain password matches the hashed one.
Examples
This creates a hashed version of "password123".
FastAPI
hashed = pwd_context.hash("password123")This checks if "password123" matches the hashed password.
FastAPI
valid = pwd_context.verify("password123", hashed)This will return False because the password does not match.
FastAPI
valid = pwd_context.verify("wrongpass", hashed)Sample Program
This FastAPI app lets users register with a hashed password and login by verifying the password safely.
Passwords are never stored in plain text.
FastAPI
from fastapi import FastAPI, HTTPException from pydantic import BaseModel from passlib.context import CryptContext app = FastAPI() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") fake_db = {} class User(BaseModel): username: str password: str @app.post("/register") async def register(user: User): if user.username in fake_db: raise HTTPException(status_code=400, detail="User already exists") hashed_password = pwd_context.hash(user.password) fake_db[user.username] = hashed_password return {"msg": "User registered successfully"} @app.post("/login") async def login(user: User): hashed_password = fake_db.get(user.username) if not hashed_password: raise HTTPException(status_code=400, detail="User not found") if not pwd_context.verify(user.password, hashed_password): raise HTTPException(status_code=400, detail="Incorrect password") return {"msg": "Login successful"}
OutputSuccess
Important Notes
Never store plain passwords; always hash them before saving.
bcrypt automatically adds a random salt to make hashes unique.
Use a strong hashing library like passlib for easy and secure hashing.
Summary
Password hashing protects user data by hiding real passwords.
Use hash() to create hashes and verify() to check passwords.
FastAPI works well with passlib for secure password handling.