FastAPI 提供内置工具(OAuth2PasswordBearer、安全实用程序)来实现身份验证,通常使用 OAuth2 密码流和 JWT 令牌。该模式结合令牌颁发(登录)和在受保护的路由上验证令牌的依赖项。
在登录时对密码进行哈希处理并颁发 JWT
python
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, : }
