【问题标题】:How to return a custom response object from the Django rest framework's custom Authentication class如何从 Django REST 框架自定义身份验证类返回自定义响应对象
【发布时间】:2017-03-01 00:34:39
【问题描述】:

我已经为此苦苦思索了将近 3-4 天。

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

我的问题是,我正在尝试找到一种返回自定义响应的方法,即;验证码HTML直接从认证类到前端,从而实现我认为没有认证相关代码。

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

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

我相信,从这里返回响应是不可能的。

我希望有人想出办法解决这个问题。

提前谢谢你!

【问题讨论】:

    标签: django authentication django-rest-framework captcha


    【解决方案1】:

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

    根据DRF docs,任何身份验证逻辑都应该重写 authenticate 方法,并且还必须重写 authenticate_header,这样如果在 authenticate 方法中引发异常,您可以从 authenticate_header 方法返回一个字符串,该字符串将用作 www-Authenticate 标头的值。

    以下是实现的工作原理。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 2019-10-26
      • 2017-01-07
      • 2020-03-16
      • 2017-10-27
      相关资源
      最近更新 更多