user-wsc/Utils/Authentication/TokenUtil.py

52 lines
1.4 KiB
Python
Raw Normal View History

2022-10-20 16:29:54 +08:00
import jwt
from jwt import PyJWTError
from datetime import datetime, timedelta
from fastapi import HTTPException, status, Header
from Utils.Authentication import Config
def create_token(*, data: dict, expires_delta: timedelta = None):
2022-11-01 01:56:57 +08:00
to_encode = dict()
# 载入用户信息
user_info = data.copy()
to_encode.update({"user_info": user_info})
2022-10-20 16:29:54 +08:00
# 设置过期时间
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
2022-11-01 01:56:57 +08:00
to_encode.update({"exp": expire})
2022-10-20 16:29:54 +08:00
# Token编码
encoded_jwt = jwt.encode(to_encode, Config.SECRET_KEY, algorithm=Config.ALGORITHM)
return encoded_jwt
def decode_token(token: str):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Token",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, Config.SECRET_KEY, algorithms=[Config.ALGORITHM])
except PyJWTError:
raise credentials_exception
return payload
async def get_token_header(authorization: str = Header(...)):
"""
获取Token并验证
:param authorization:
:return: uid
"""
token = authorization.split(' ')[-1] # 获取token
openid = decode_token(token) # 验证token
if not openid:
raise HTTPException(status_code=400, detail="无效Token")