
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
'Python > FastAPI' 카테고리의 다른 글
| [FastAPI] MS SQL Server 연결 중 _SQLAllocHandle 예외 (1) | 2024.11.19 |
|---|---|
| [FastAPI] AttributeError - 'ScalarResult' object has no attribute 'field' (0) | 2024.11.17 |
| Mac 환경에서 mysqlclient 설치 시, pkg-config가 설치되어 있지 않다면 만날 수 있는 에러 - Can not find valid pkg-config name. (0) | 2024.11.10 |
| [FastAPI] LifeSpan Events에 대해 알아보자 (0) | 2024.11.09 |
| Sqlacodegen 사용하여 SqlAlchemy Model 자동생성하기 (0) | 2024.11.07 |