目录
1、安装PyJWT
2、对信息加密及解密
3、配置登录视图和及url
4、登录装饰器
5、在验证有登录权限的的视图中登录
PyJWT的使用
1、安装PyJWT
pip isntall pyjwt
2、对信息加密及解密
import jwt
import datetime
from jwt import exceptions
# 加密盐
JWT_SALT = "ds()udsjo@jlsdosjf)wjd_#(#)$"
def create_token(payload, timeout=20):
# 声明类型,声明加密算法
headers = {
"type": "jwt",
"alg": "HS256"
}
# 设置过期时间
payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=36000)
result = jwt.encode(payload=payload, key=JWT_SALT, algorithm="HS256", headers=headers).decode("utf-8")
# 返回加密结果
return result
def parse_payload(token):
"""
用于解密
:param token:
:return:
"""
result = {"status": False, "data": None, "error": None}
try:
# 进行解密
verified_payload = jwt.decode(token, JWT_SALT, True)
result["status"] = True
result['data'] = verified_payload
except exceptions.ExpiredSignatureError:
result['error'] = 'token已失效'
except jwt.DecodeError:
result['error'] = 'token认证失败'
except jwt.InvalidTokenError:
result['error'] = '非法的token'
return result
3、配置登录视图和及url
class LoginView(View):
"""登录"""
def post(self, request):
data_dict = json.loads(request.body.decode())
username = data_dict.get('username', None)
password = data_dict.get('password', None)
user = authenticate(request, username=username, password=password) # 用户名密码认证
if user is not None:
token = create_token({"username": username}) # jwt加密生成token
return JsonResponse({"status": 200, "token": token})
else:
return JsonResponse({"status": 400, "error": "用户名密码错误"})
在登录成功后会返回一个token
4、登录装饰器
用于验证用户是否登录成功
def decorator_login_require(func):
"""登录装饰器"""
def wrapper(request, *args, **kwargs):
authorization = request.META.get('HTTP_AUTHORIZATION', '') # 获取Headers里的Authorization值
if authorization:
payload = parse_payload(authorization) # 解密token
status = payload['status']
if status:
username = payload['data']['username']
user = UserProfile.objects.filter(username=username).first() # 解密后查询
if user:
request.user = user
return func(request, *args, **kwargs)
else:
return JsonResponse({"status": 401, "msg": payload['error']})
return JsonResponse({"status": 401, "msg": "对不起,您还未登录"})
return wrapper
5、在验证有登录权限的的视图中登录
将decorator_login_require装饰器装饰在类视图的post方法上
class OnlyLoginCanView(View)
"""只有登录的用户才能访问的视图"""
@method_decorator(decorator_login_require)
def post(self, request):
# 具体的功能逻辑
return JsonResponse({"status": 200, "msg": "成功"})
配置OnlyLoginCanView类视图的url后在请求时在Headers里需要添加参数名为Authorization值为登录时返回的token值登录,否则不能访问该视图
成功时
当传入的Authorization值不是登录时返回的token值时不能成功登录