利用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