jQuery Ajax calls and the Html.AntiForgeryToken()

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

    I was just implementing this actual problem in my current project. i did it for all ajax-POSTs that needed an authenticated user.

    First off i decided to hook my jquery ajax calls so i do not to repeat myself too often. this javascript snippet ensures all ajax (post) calls will add my request validation token to the request. Note: the name __RequestVerificationToken is used by the .Net framework so i can utilize the standard Anti-CSRF features as shown below.

    $(document).ready(function () {
        var securityToken = $('[name=__RequestVerificationToken]').val();
        $('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);
                }
            }
        });
    });
    

    In your Views where you need the token to be available to the above javascript just use the common HTML-Helper. You can basically add this code whereever you want. I placed it within a if(Request.IsAuthenticated) statement:

    @Html.AntiForgeryToken() // you can provide a string as salt when needed which needs to match the one on the controller
    

    In your controller simply use the standard ASP.Net MVC Anti-CSRF mechanism. I did it like this (though i actually used Salt).

    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public JsonResult SomeMethod(string param)
    {
        // do something
        return Json(true);
    }
    

    With Firebug or a similar tool you can easily see how your POST requests now have a __RequestVerificationToken parameter appended.

提交回复
热议问题