如何 return 来自 Django 休息框架自定义身份验证的自定义响应对象 class

How to return a custom response object from the Django rest framework's custom Authentication class

我已经为此绞尽脑汁将近 3-4 天了。

让我解释一下情况。我有一个基于 DRF(Django REST Framework)class 的视图,带有自定义身份验证 class。据我了解,您可以覆盖 DRF 的 BaseAuthentication class 的身份验证方法来实现您的自定义身份验证,而如果身份验证失败,您只能引发 DRF 提供的预定义异常。

我的问题是,我正在尝试找到一种方法来 return 自定义响应,即;验证码HTML直接从鉴权class传到前端,实现我认为无鉴权相关代码

为了更好地了解我的情况,我在下面提供了一个伪代码。

class ExampleView(APIView):
    authentication_classes = (ExampleCustomAuth, )

    def get(self, request):
        pass

这是风景,这部分绝对没问题。

class ExampleCustomAuth(BaseAuthentication):

    def authenticate(self, request):
        req = request
        request = req._request
        {
            This part of code decides if its required for a 
            captcha or not 
        }

        if captcha_required:
            response = HttpResponse()
            response.status_code = 401
            response['WWW-Authenticate'] = 'Captcha" id="%s"'% (id)
            response.content = loader.render_to_string('captcha.html')

            return response # This is where it goes wrong

我相信,从这里 return 不可能得到回应。

我希望有人已经找到解决这个问题的方法。

提前致谢!

嗯,我终于想出了一个让它工作的方法。

根据 DRF docs,对于任何身份验证逻辑都应重写身份验证方法,并且还必须重写 authenticate_header,因此如果您在身份验证方法中引发异常,您可以 return 来自 authenticate_header 方法的字符串,将用作 www-Authenticate header.

的值

下面是实现的工作原理。

class ExampleCustomAuth(BaseAuthentication):

    def authenticate(self, request):
        req = request
        request = req._request
        {
            This part of code decides if its required for a 
            captcha or not 
        }

        if captcha_required:
            raise exceptions.AuthenticationFailed(loader.render_to_string('captcha.html'))

    def authenticate_header(self, request):
        return 'Captcha" id="%s"'% (id)