Drf认证组件
四、Drf认证组件
4.1 快速使用
from django.shortcuts import render,HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
# Create your views here.
class Myauthentication(BaseAuthentication):
"""
用户认证:
1、读取请求传递过来的token
2、校验合法性
3、返回值
--3.1返回元组,如(11,22),认证成功,request.user=11,request.auth=22
--3.2抛出异常,认证失败,返回错误信息
--3.3返回None,多个认证类[类1,类2,类3,类4..。。]-->匿名用户
"""
def authenticate(self, request):
#获取token
token=request.GET.get('token')
if token:
#如果token校验成功,则返回一个元组(用户名和token),request.user=元组[0],request.auth=元组[1]
return 'sally',token
#如果校验失败则抛出异常
raise AuthenticationFailed({
'code':2000,'error':'认证失败'})
class LoginView(APIView):
#该视图无需认证
authentication_classes = []
def get(self,request):
#user和auth都为None
print('user', request.user)
print('auth', request.auth)
return Response('login')
class UserView(APIView):
#该视图要需认证
authentication_classes = [Myauthentication,]
def get(self, request):
#user和auth为认证类Myauthentication返回的结果
print('user',request.user)
print('auth',request.auth)
return Response('user')
class OrderView(APIView):
#该视图要需认证
authentication_classes = [Myauthentication, ]
def get(self, request):
#user和auth为认证类Myauthentication返回的结果
print(request.user)
print(request.auth)
return Response('order')
认证的全局配置:
上个示例中,需要在每个视图中应用认证类,比较麻烦。
可以在settings.py中做全局配置
REST_FRAMEWORK = {
"UNAUTHENTICATED_USER":</