利用jwt的认证,快速完成自定义认真类的实现


# 认证类的实现
from rest_framework.authentication import BaseAuthentication
from rest_framework_jwt.settings import api_settings
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
from rest_framework import exceptions
from user import models
import jwt

class TokenAuthenticate(BaseAuthentication):
def authenticate(self, request):
# 取出前端传过来的token值
token = request.META.get('HTTP_TOKEN')
try:
# 通过token串获取payload(荷载),验证签名,检查过期时间
payload = jwt_decode_handler(token)
# 签名过期抛异常
except jwt.ExpiredSignature:
msg = '签名过期'
raise exceptions.AuthenticationFailed(msg)
# 签名解析出错抛异常
except jwt.DecodeError:
msg = '签名错误'
raise exceptions.AuthenticationFailed(msg)
# 签名校验不合法也抛异常
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed('token不正确')
# 通过payload获取当前用户:通过user_id去auth_user表中获取当前用户
user_obj = models.Consumer.objects.filter(pk=payload['user_id']).first()
# 返回当前登录用户和token串
return user_obj, token

posted @ 2021-12-08 20:10  点滴180  阅读(101)  评论(0)    收藏  举报