본문 바로가기

Python/FastAPI

[FastAPI] PassLib와 Bcrypt를 활용한 패스워드 해싱

How to Password Hashing in FastAPI?

In FastAPI Official docs, it recommand "PassLib" Python package to handle password hashes. The recommended algorithm is "Bcrypt".

if you use poetry, then follow this command.

poetry add "passlib[bcrypt]"


we can encrypt plaintext passwords to use PassLib, and create module that validate encrypt string is from the received plaintext.

from passlib.context import CryptContext

class Crypto:

    def __init__(self):
        self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

    def encrypt(self, plain_password):
        return self.pwd_context.hash(plain_password)

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

PassLib context

The PassLib context also has functionality to use different hashing algorithms, including deprecated old ones only to allow verifying them, etc.

For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Bcrypt.

And be compatible with all of them at the same time.

Reference