import jwt
from datetime import datetime, timedelta, timezone
payload = {
'user_id': user_obj.id,
'exp': datetime.utcnow() + timedelta(days=3) # Token 过期时间
}
token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
# 生成token
def user_check_login(request):
try:
token = request.headers.get('Authorization')
if token and token.startswith('Bearer '):
token = token[7:] # 去掉 'Bearer ' 部分
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
if payload:
user_id = payload.get('user_id')
user = User.objects.filter(id=user_id).first()
return user
else:
return None
return None
except Exception as e:
print(f"Error decoding JWT: {e}")
return None
# 验证token,获取用户
需自行导包,User类为你的用户类