一、创建自定义类
import datetime
from django.conf import settings
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed
from base.models import User
import jwt
from jwt import exceptions
def create_token(payload): # 创建token
salt = settings.SECRET_KEY
headers = {
'typ': 'jwt',
'alg': 'HS256',
}
payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=3) # 设置token的有效时间
token = jwt.encode(payload=payload, key=salt, headers=headers, algorithm='HS256')
return token
class MyAuthentication(BasicAuthentication): #继承基础的认证类
def authenticate(self, request):
token = request.META.get('HTTP_AUTHORIZATION')
if token:
salt = settings.SECRET_KEY
payload = None
try:
payload = jwt.decode(token, salt, algorithms='HS256', verify=True)
except exceptions.ExpiredSignatureError:
raise AuthenticationFailed({'code': '1000', 'msg': 'token已经失效'})
except jwt.DecodeError:
raise AuthenticationFailed({'code': '1001', 'msg': 'token认证失败'})
except jwt.InvalidTokenError:
raise AuthenticationFailed({'code': '1002', 'msg': '非法的token'})
user_objects = User.objects.filter(username=payload['user']['username']).first()
return user_objects, token
else:
raise AuthenticationFailed({'code': '1003', 'msg': '没有获取到token'})
def authenticate_header(self, request):
return 'API'
二、全局使用
REST_FRAMEWORK = {
'UNAUTHENTICATED_USER': None,
'DEFAULT_AUTHENTICATION_CLASSES': ['utils.auth.MyAuthentication'], # 全局使用,settings文件注册认证类
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Django-rest-framework(DRF)如何实现自定义认证
发表评论 取消回复