【问题标题】:Django jQuery CSRF fix does not work on iPadDjango jQuery CSRF 修复在 iPad 上不起作用
【发布时间】:2012-01-04 13:13:18
【问题描述】:

here 给出的 Django jQuery 修复程序在 iPad 上不起作用。关于如何使其工作的任何想法?

修复代码:

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

编辑

澄清一下:

这是一个示例 js:

function foo() {
    data = {some:"datahere"}
    jQuery.ajax({
        url: "urlhere",
        type: "POST",
        data: data,
        success: function() {
            // do something
        },
        error: function() {
            alert("Could not send ajax request with POST");
        }
    })
}

在常规浏览器中,永远不会调用错误函数,但在 iPad 上我总是会收到警报(至少在 iOS sim 中)。当我看到 django 日志时,我看到这些请求返回了代码 403。如果添加 @csrf_exempt 装饰器,一切都可以在 iPad 上运行,所以我很确定是 csrf 失败了。

【问题讨论】:

  • “不能在 iPad 上运行”究竟是什么意思?
  • 对不起。刚刚更新了问题。谢谢@Hoff

标签: javascript jquery django ipad csrf


【解决方案1】:

iPad 出于某种原因并不总是能获取 CSRF cookie 的值,因此 jQuery csrf fix 不起作用,因为它无法读取 cookie 的值。

解决方案是确保在与需要 csrf 的客户端交互的视图上使用 ensure_csrf_cookie 装饰器将 cookie 发送到客户端。

示例:

# models.py
from django.views.decorators.csrf import csrf_protect, csrf_exempt, requires_csrf_token, ensure_csrf_cookie

@ensure_csrf_cookie
def fooview(request):
    # do something here
    pass

【讨论】:

  • 这对我使用 iOS 版本 6.1.3 的 iPad 不起作用。我仍然收到 403 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 2012-04-27
相关资源
最近更新 更多