jQuery Ajax calls and the Html.AntiForgeryToken()

前端 未结 20 2544
鱼传尺愫
鱼传尺愫 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 17:23

    I know there are a lot of other answers, but this article is nice and concise and forces you to check all of your HttpPosts, not just some of them:

    http://richiban.wordpress.com/2013/02/06/validating-net-mvc-4-anti-forgery-tokens-in-ajax-requests/

    It uses HTTP headers instead of trying to modify the form collection.

    Server

    //make sure to add this to your global action filters
    [AttributeUsage(AttributeTargets.Class)]
    public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute
    {
        public override void OnAuthorization( AuthorizationContext filterContext )
        {
            var request = filterContext.HttpContext.Request;
    
            //  Only validate POSTs
            if (request.HttpMethod == WebRequestMethods.Http.Post)
            {
                //  Ajax POSTs and normal form posts have to be treated differently when it comes
                //  to validating the AntiForgeryToken
                if (request.IsAjaxRequest())
                {
                    var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
    
                    var cookieValue = antiForgeryCookie != null
                        ? antiForgeryCookie.Value 
                        : null;
    
                    AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
                }
                else
                {
                    new ValidateAntiForgeryTokenAttribute()
                        .OnAuthorization(filterContext);
                }
            }
        }
    }
    

    Client

    var token = $('[name=__RequestVerificationToken]').val();
    var headers = {};
    headers["__RequestVerificationToken"] = token;
    
    $.ajax({
        type: 'POST',
        url: '/Home/Ajax',
        cache: false,
        headers: headers,
        contentType: 'application/json; charset=utf-8',
        data: { title: "This is my title", contents: "These are my contents" },
        success: function () {
            ...
        },
        error: function () {
            ...
        }
    });
    

提交回复
热议问题