【问题标题】:Django jQuery ajax post to https failsDjango jQuery ajax 发布到 https 失败
【发布时间】:2013-08-14 11:12:42
【问题描述】:

我正在编写一个 chrome 扩展,它使用 GET 和 POST ajax 调用一个由 Django 和 Tastypie 制作的 api。

GET ajax 调用成功,我可以访问数据。但是 POST 调用仅在生产中失败,因为 api 托管在 https:// 上,在本地环境中它可以工作 (htt://localhost:8000)。

我在标头中提供了正确的 CSRF 令牌。 似乎错误发生在这里:https://github.com/toastdriven/django-tastypie/blob/master/tastypie/authentication.py#L259 其中 api 需要 Referer 标头来检查调用是否安全。

似乎无法在我的 ajax 标头中直接设置 Referer 值,除非标头的名称以 X- 开头。

提前感谢您提供解决此问题的任何解决方案或提示。

马克西姆。

【问题讨论】:

标签: django jquery google-chrome-extension tastypie


【解决方案1】:

original source of that method 中解释了该检查的原因:

# Suppose user visits http://example.com/
# An active network attacker (man-in-the-middle, MITM) sends a
# POST form that targets https://example.com/detonate-bomb/ and
# submits it via JavaScript.
#
# The attacker will need to provide a CSRF cookie and token, but
# that's no problem for a MITM and the session-independent
# nonce we're using. So the MITM can circumvent the CSRF
# protection. This is true for any HTTP connection, but anyone
# using HTTPS expects better! For this reason, for
# https://example.com/ we need additional protection that treats
# http://example.com/ as completely untrusted. Under HTTPS,
# Barth et al. found that the Referer header is missing for
# same-domain requests in only about 0.2% of cases or less, so
# we can use strict Referer checking.

因此,您可能会或可能不会从推荐人检查中受益 - 由您决定。

如果您想覆盖它,只需将您的模型设置为使用SessionAuthentication 的子类进行身份验证,并根据您的需要覆盖is_authenticated(self, request, **kwargs) 函数。原始方法非常简洁,所以老实说,我只是复制粘贴它并删除有问题的if request.is_secure(): 块,而不是欺骗超类认为请求具有引用者。

【讨论】:

    【解决方案2】:

    您还可以通过使请求对象认为它不是由安全调用发出的,从而跳过检查 AJAX 调用中的引用者。这样,您就可以保留 CSRF 检查和其他所有内容,只需跳过引用。这是一个示例中间件:

    class UnsecureAJAX(object):
        def process_request(self, request):
            setattr(request, '_is_secure_default', request._is_secure)
            def _is_secure():
                if request.is_ajax():
                    return False
                else:
                    return request._is_secure_default()
            setattr(request, '_is_secure', _is_secure)
    

    【讨论】:

      【解决方案3】:

      现在技术上也可以使用webRequest API 更改请求的Referer 部分。

      您需要一个具有["blocking", "requestHeaders"] 选项和相应权限的onBeforeSendHeaders 侦听器。然后就可以拦截自己的请求,修改header了。

      【讨论】:

        猜你喜欢
        • 2018-07-05
        • 1970-01-01
        • 2011-12-06
        • 1970-01-01
        • 2011-06-30
        • 2018-11-11
        • 1970-01-01
        • 1970-01-01
        • 2013-10-07
        相关资源
        最近更新 更多