如何获得在DRF视图中进行身份验证时成功的身份验证类(或类名)?

时间:2018-08-09 08:13:47

标签: django django-rest-framework django-authentication

假设我有一个看法

from rest_framework import viewsets


class SampleViewset(viewsets.ModelViewSet):
    serializer_class = SampleSerializer
    queryset = Sample.objects.all()
    authentication_classes = (FirstAuthClass, SecondAuthClass, ThirdAuthClass)

    def get_success_auth_class(self, request, *args, **kwargs):
        # What logic should I use here ????
        return success_auth_class


然后,应该在 get_success_auth_class() 方法中使用什么逻辑?

换一种说法, 如何获取在DRF视图中进行身份验证时成功的身份验证类(或类名称)?

1 个答案:

答案 0 :(得分:2)

DRF请求类具有名为successful_authenticator的属性,该属性将返回使用的身份验证实例类的实例。         来验证请求或None

class SampleViewset(viewsets.ModelViewSet):
    serializer_class = SampleSerializer
    queryset = Sample.objects.all()
    authentication_classes = (FirstAuthClass, SecondAuthClass, ThirdAuthClass)

    def get_success_auth_class(self, request, *args, **kwargs):
        for auth_class in self.authentication_classes:
            if isinstance(request.successful_authenticator, auth_class):
                return auth_class
        return None


在此处引用源代码

@property
def successful_authenticator(self):
    """
    Return the instance of the authentication instance class that was used
    to authenticate the request, or `None`.
    """
    if not hasattr(self, '_authenticator'):
        with wrap_attributeerrors():
            self._authenticate()
    return self._authenticator


参考

Github source code