jQuery Ajax calls and the Html.AntiForgeryToken()

前端 未结 20 2350
鱼传尺愫
鱼传尺愫 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:28

    I like the solution provided by 360Airwalk, but it may be improved a bit.

    The first problem is that if you make $.post() with empty data, jQuery doesn't add a Content-Type header, and in this case ASP.NET MVC fails to receive and check the token. So you have to ensure the header is always there.

    Another improvement is support of all HTTP verbs with content: POST, PUT, DELETE etc. Though you may use only POSTs in your application, it's better to have a generic solution and verify that all data you receive with any verb has an anti-forgery token.

    $(document).ready(function () {
        var securityToken = $('[name=__RequestVerificationToken]').val();
        $(document).ajaxSend(function (event, request, opt) {
            if (opt.hasContent && securityToken) {   // handle all verbs with content
                var tokenParam = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
                opt.data = opt.data ? [opt.data, tokenParam].join("&") : tokenParam;
                // ensure Content-Type header is present!
                if (opt.contentType !== false || event.contentType) {
                    request.setRequestHeader( "Content-Type", opt.contentType);
                }
            }
        });
    });
    

提交回复
热议问题