2

我正在编写一个 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-.

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

马克西姆。

4

3 回答 3

1

该方法的原始来源中解释了该检查的原因:

# 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():块,而不是欺骗超类认为请求具有引用者。

于 2013-08-17T15:29:22.310 回答
0

您还可以通过使请求对象认为它不是由安全调用发出的,从而跳过检查 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)
于 2015-03-23T12:41:45.750 回答
0

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

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

于 2015-03-23T12:46:01.280 回答