在需要认证的视图类里加上authentication_classes = [认证组件1类名,认证组件2类名....]
示例如下:
seralizers.py
from rest_framework import serializers from app01 import models class PublishSerializers(serializers.ModelSerializer): class Meta: model = models.Publish fields = ‘__all__‘
auth.py
from rest_framework.authentication import BaseAuthentication from rest_framework import exceptions from app01 import models class TokenAuth(BaseAuthentication): def authenticate(self,request): ‘‘‘函数名必须叫authenticate‘‘‘ # 验证条件根据需求设置(此示例为需要有token值) token = request.GET.get(‘token‘) token_obj = models.Token.objects.filter(token=token).first() if not token_obj: # 如果验证失败,需要跑出AuthenticationFailed错误 raise exceptions.AuthenticationFailed("验证失败!") else: user = token_obj.user # 如果验证成功,需要返回一个元组,分别是用户以及验证类的实例对象,然后内部会赋值给request.user和request.auth return user.username,token_obj
views.py
from rest_framework import viewsets from app01.auth import TokenAuth class PublishViewSet(viewsets.ModelViewSet): # 在这里配置authentication_classes # 注意,值为一个列表,可以放多个认证组件类名 authentication_classes = [TokenAuth] queryset = models.Publish.objects.all() serializer_class = serializer.PublishSerializers
在setting.py里配置如下:
REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["app01.auth.TokenAuth",] }
这样配置之后,每个视图类都要经过认证成功之后才能执行,
原文:https://www.cnblogs.com/fu-yong/p/9063223.html