Django:csrf_exempt在其他服务器发送请求时不起作用?

时间:2017-01-13 06:14:50

标签: django csrf django-csrf

views.py

class OrderPayCheckView(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(OrderPayCheckView, self).dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return redirect(reverse("home"))

我使用了第三方服务(我是客户端),它将Notification request(POST)发送给OrderPayCheckView

由于此POST request不是来自我的应用,因此我认为此视图应使用csrf_exempt进行修饰,以便它不再需要csrf token

当我使用POSTMAN进行测试时效果非常好:它将重定向的模板页面显示为响应正文。

但是,当此第三方服务(服务器)尝试向此视图发送POST请求时,它会显示csrf-token身份验证错误,如下所示:

(由于错误是韩文,我翻译它)

 REQUEST HTTP BODY : imp_uid=imp_1234567890&merchant_uid=merchant_1234567890&status=ready
 REQUEST HTTP STATUS : 403
 REQUEST HTTP BODY : 
 <!DOCTYPE html> 
    <html lang="en"> 
    <head> 
        <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
        <meta name="robots" content="NONE,NOARCHIVE"> 
        <title>403 Forbidden</title> 
    </head> 
    <body> 
        <div id="summary"> 
            <h1>Forbidden <span>(403)</span></h1> 
            <p> CSRF authentication failed. </p>
            <p> The reason this message shown up is that this https site require "reference header" from your browser, but didn't receive anything abuout it. This header is required for security.</p>
        </div>
    </body> 
</html>

它有什么问题?发件人是否必须在其请求中添加特定的reference header

1 个答案:

答案 0 :(得分:-1)

编辑:这不是正确的答案,也没有必要

您没有装饰post方法

@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
    return super(OrderPayCheckView, self).dispatch(request, *args, **kwargs)

@method_decorator(csrf_exempt)
def post(self, request, *args, **kwargs):
    return redirect(reverse("home"))