DRF认证系统的实现

自定义实例

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response from rest_framework.request import Request from goods.serializers import GoodsSerializer from rest_framework.exceptions import APIException # Create your views here. from goods.models import Goods class MyAuthentication(object): def authenticate(self,request): token = request.query_params.get('token') if token == 'abc': return ('aaa','bbb') raise APIException('认证失败') class GoodsListView(APIView): authentication_classes = [MyAuthentication,] def get(self,request,*args,**kwargs): print(request.user,request.auth) goods = Goods.objects.all() goods_serializer = GoodsSerializer(goods,many=True) return Response(goods_serializer.data)

流程

在使用的时候 使用 BaseAuthentication类

这里可以把认证 当成用户登录状态的判断

登录时不需要 认证,登录之后的访问都需要 进行 登录用户身份的确认。

可以全局添加认证,然后把登录,或者主页等不需要 登录的视图,设置为 authentication_classes= []

当 authenticate 不处理返回None的时候,匿名用户的设置

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES":[],
    # "UNAUTHENTICATED_USER":lambda :'匿名用户',
    "UNAUTHENTICATED_USER":None, # "UNAUTHENTICATED_TOKEN":lambda :'没有验证信息', "UNAUTHENTICATED_TOKEN":None, }

BasicAuthentication

    def authenticate_header(self, request): return 'Basic realm="%s"' % 'api

读书使人心眼明亮

猜你喜欢

转载自www.cnblogs.com/wind1024/p/9948401.html