jQuery Ajax calls and the Html.AntiForgeryToken()

前端 未结 20 2548
鱼传尺愫
鱼传尺愫 2020-11-22 16:34

I have implemented in my app the mitigation to CSRF attacks following the informations that I have read on some blog post around the internet. In particular these post have

20条回答
  •  一个人的身影
    2020-11-22 17:27

    found this very clever idea from https://gist.github.com/scottrippey/3428114 for every $.ajax calls it modifies the request and add the token.

    // Setup CSRF safety for AJAX:
    $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
        if (options.type.toUpperCase() === "POST") {
            // We need to add the verificationToken to all POSTs
            var token = $("input[name^=__RequestVerificationToken]").first();
            if (!token.length) return;
    
            var tokenName = token.attr("name");
    
            // If the data is JSON, then we need to put the token in the QueryString:
            if (options.contentType.indexOf('application/json') === 0) {
                // Add the token to the URL, because we can't add it to the JSON data:
                options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
            } else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
                // Append to the data string:
                options.data += (options.data ? "&" : "") + token.serialize();
            }
        }
    });
    

提交回复
热议问题