jQuery Ajax calls and the Html.AntiForgeryToken()

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

    Slight improvement to 360Airwalk solution. This imbeds the Anti Forgery Token within the javascript function, so @Html.AntiForgeryToken() no longer needs to be included on every view.

    $(document).ready(function () {
        var securityToken = $('@Html.AntiForgeryToken()').attr('value');
        $('body').bind('ajaxSend', function (elm, xhr, s) {
            if (s.type == 'POST' && typeof securityToken != 'undefined') {
                if (s.data.length > 0) {
                    s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
                }
                else {
                    s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
                }
            }
        });
    });
    

提交回复
热议问题