31 lines
812 B
Python
31 lines
812 B
Python
import jwt
|
|
import datetime
|
|
import configparser
|
|
|
|
# 读取配置文件
|
|
config = configparser.ConfigParser()
|
|
config.read('backend/config.conf')
|
|
SECRET_KEY = config['jwt']['key']
|
|
|
|
def create_token(data: dict, expires_delta: datetime.timedelta):
|
|
"""
|
|
创建 JWT Token
|
|
"""
|
|
to_encode = data.copy()
|
|
expire = datetime.datetime.utcnow() + expires_delta
|
|
to_encode.update({"exp": expire})
|
|
token = jwt.encode(to_encode, SECRET_KEY, algorithm="HS256")
|
|
return token
|
|
|
|
def verify_token(token: str):
|
|
"""
|
|
验证 JWT Token
|
|
"""
|
|
try:
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
|
|
return payload
|
|
except jwt.ExpiredSignatureError:
|
|
raise ValueError("Token has expired")
|
|
except jwt.InvalidTokenError:
|
|
raise ValueError("Invalid token")
|