如何在django rest框架中传递多个身份验证类?

如何在django rest框架中传递多个身份验证类?,django,authentication,django-rest-framework,Django,Authentication,Django Rest Framework,我想创建一个api,它可以使用client_id和client_secret以及访问令牌进行访问。 要使用client_id和client_secret访问api,我有如下自定义身份验证类:- class ClientAuthentication(authentication.BaseAuthentication): @staticmethod def get_client_credentials(request): try: client

我想创建一个api,它可以使用client_id和client_secret以及访问令牌进行访问。 要使用client_id和client_secret访问api,我有如下自定义身份验证类:-

class ClientAuthentication(authentication.BaseAuthentication):
    @staticmethod
    def get_client_credentials(request):
        try:
            client_id = request.headers.get('CLIENTID')
            client_secret = request.headers.get('CLIENTSECRET')
        except:
            raise AuthenticationFailed
        return {
            'client_id': client_id,
            'client_secret': client_secret
        }

    def authenticate(self, request):
        credentials = self.get_client_credentials(request)

        client_instance = Application.objects.filter(
            client_id=credentials['client_id'],
            client_secret=credentials['client_secret'],
        ).first()

        if not client_instance:
            raise AuthenticationFailed
        return client_instance, None

    def get_user_application(self, request):
        credentials = self.get_client_credentials(request)

        application_instance = Application.objects.filter(
            client_id=credentials['client_id'],
            client_secret=credentials['client_secret'],
        ).first()

        if not application_instance:
            raise AuthenticationFailed
        return application_instance, None
我想使用的另一个身份验证类是默认的OAuth2Authentication 我尝试将viewset的身份验证类传递为:

authentication_classes = [ClientAuthentication | OAuth2Authentication]
但这给了我一个错误。
如何实现这一点?

您应该通过authenticate\u头来区分身份验证程序。当AuthenticationClass(在authenticate方法中)读取不正确的authenticate_头时,应返回None,因此请求将继续到下一个验证器。例如,在令牌身份验证中

def authenticate(self, request):
    auth = get_authorization_header(request).split()

    if not auth or auth[0].lower() != self.keyword.lower().encode():
        return None
    ...
如果不返回None,则authenticate将引发APIException,因此不会调用下一个身份验证类

此外,如果要使用多个身份验证类,则必须在设置中定义它们,如中所示:


或者在视图中定义它们。

DRF不支持对
authentication\u类
进行位操作,但在
permission\u类
authentication\u类=(ClientAuthentication,OAuth2Authentication)
我也尝试使用逗号。它不起作用@AndreyNelubin
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}