REST_FRAMEWORK = {
‘DEFAULT_AUTHENTICATION_CLASSES‘: (
‘rest_framework_jwt.authentication.JSONWebTokenAuthentication‘,
‘rest_framework.authentication.SessionAuthentication‘,
‘rest_framework.authentication.BasicAuthentication‘,
)
}
from rest_framework.exceptions import AuthenticationFailed
class MyAuthentication(object):
# authenticate authenticate_header 两个方法是必须有的,authenticate用来写我们自己的认证方式,authenticate_header直接写pass就行,不写会抛错,缺少authenticate_header方法
def authenticate(self, request):
self.token = request._request.GET.get(‘token‘)
if not self.token:
raise AuthenticationFailed(‘用户认证失败‘) # 如果认证失败,就抛出一个AuthenticationFailed异常
return (‘wbj‘, self.token) # 如果认证通过,就行返回一个元组,第一个元素是用户身份(user),第二个是auth
def authenticate_header(self, request):
pass
class Book(APIView):
authentication_classes = [MyAuthentication, ]
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def get(self, request):
# get a book
return HttpResponse(json.dumps({‘code‘: ‘20000‘}))
def post(self, request):
return HttpResponse(json.dumps({‘code‘: ‘20000‘}))
def put(self, request):
# update a book
return HttpResponse(json.dumps({‘code‘: ‘20000‘}))
def delete(self, request):
# delete a book
return HttpResponse(json.dumps({‘code‘: ‘20000‘}))
原文:https://www.cnblogs.com/wangbaojun/p/10991052.html