Add method to generate access token
This commit is contained in:
34
main.py
34
main.py
@@ -70,6 +70,40 @@ async def global_auth(request: Request):
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
def generate_access_token(username: str, password: str) -> str:
|
||||
"""
|
||||
根据用户名和密码生成JWT access token
|
||||
|
||||
参数:
|
||||
username: 用户名
|
||||
password: 密码
|
||||
|
||||
返回:
|
||||
JWT access token字符串
|
||||
"""
|
||||
|
||||
if username != "tjwater" or password != "tjwater@123":
|
||||
raise ValueError("用户名或密码错误")
|
||||
|
||||
# 安全配置
|
||||
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
|
||||
ALGORITHM = "HS256"
|
||||
TOKEN_EXPIRE = 120 # 分钟
|
||||
|
||||
# 创建密码上下文
|
||||
pwd_ctx = CryptContext(schemes=["bcrypt"])
|
||||
|
||||
# 创建token载荷
|
||||
payload = {
|
||||
"sub": username, # 用户标识
|
||||
"exp": datetime.utcnow() + timedelta(minutes=TOKEN_EXPIRE) # 过期时间
|
||||
}
|
||||
|
||||
# 生成并返回JWT token
|
||||
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
|
||||
# 将 Query的信息 序列号到 redis/json, 默认不支持datetime,需要自定义
|
||||
# 自定义序列化函数
|
||||
# 序列化处理器
|
||||
|
||||
Reference in New Issue
Block a user