FastAPI cung cấp các công cụ tích hợp (OAuth2PasswordBearer, các tiện ích security) để triển khai authentication, thường dùng OAuth2 password flow với JWT token. Pattern kết hợp việc phát hành token (đăng nhập) với một dependency validate token trên các route được bảo vệ.
Hash password và phát hành một JWT khi đăng nhập
passlib.context CryptContext
jose jwt
datetime datetime, timedelta
pwd = CryptContext(schemes=[])
():
user = get_user(form.username)
user pwd.verify(form.password, user.hashed_password):
HTTPException(, )
token = jwt.encode(
{: user.username, : datetime.utcnow() + timedelta(minutes=)},
SECRET_KEY, algorithm=,
)
{: token, : }
