我已经为这事绞尽脑汁了将近3-4天了。
让我解释一下情况。我有一个基于DRF(Django REST Framework)类的视图和一个自定义身份验证类。据我所知,您可以重写DRF的BaseAuthentication类的身份验证方法来实现您的自定义身份验证,而只有在验证失败时才能引发从DRF提供的预定义异常。
我的问题是,我试图找到一种方法来返回自定义响应,即,captcha 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我相信,我们不可能从这里收回回应。
我希望有人想办法绕过这件事。
提前谢谢你!
发布于 2016-10-20 11:23:19
我终于想出办法让它起作用了。
根据DRF文档,对于任何身份验证逻辑,都应该重写身份验证方法,并且还必须重写authenticate_header,以便如果在身份验证方法中引发异常,则可以从authenticate_header方法返回一个字符串,该字符串将用作www-身份验证标头的值。
下面是实现的工作方式。
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)https://stackoverflow.com/questions/40130210
复制相似问题