How to send AntiForgeryToken (CSRF) along with FormData via jquery ajax

主宰稳场 提交于 2019-12-05 05:22:08

FINALLY FOUND THE ANSWER :

I just need to add .get(0) in the form, here's the code :

<script>
        $(document).ready(function(){
            $('#btnRXUpload').click(function () {
                var form = $('#frmRXUpload')

                if (form.valid()) {
                    var formData = new FormData(form.get(0)); //add .get(0)
                    formData.append('files', $('#frmRXUpload input[type="file"]')[0].files[0]);
                    //formData.append('__RequestVerificationToken', fnGetToken()); //remark this line

                    $.ajax({
                        type: 'POST',
                        url: '/RX/Upload',
                        data: formData,
                        contentType: false,
                        processData: false
                    })
                }
            })
        })
    </script>

You need to add the token to the request headers, not the form. Like this:

        if (form.valid()) {
            var formData = new FormData(form);
            formData.append('files', $('#frmRXUpload input[type="file"]')[0].files[0]);

            $.ajax({
                type: 'POST',
                url: '/RX/Upload',
                data: formData,
                contentType: 'multipart/form-data',
                processData: false,
                headers: {
                    '__RequestVerificationToken': fnGetToken()
                } 
            })
        }

Edit Looking back at how I solved this problem myself, I remember that the standard ValidateAntiForgeryTokenAttribute looks in the Request.Form object which doesn't always get populated for an AJAX request. (In your case, the file upload needs a multipart/form-data content type, whereas a form post for the CSRF token needs application/x-www-form-urlencoded. You set contentType=false, but the two operations need conflicting content types, which may be part of your problem). So, in order to validate the token on the server, you will need to write a custom attribute for your action method that checks for the token in the request header:

public sealed class ValidateJsonAntiForgeryTokenAttribute
                            : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        var httpContext = filterContext.HttpContext;
        var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
        AntiForgery.Validate(cookie != null ? cookie.Value : null,
                             httpContext.Request.Headers["__RequestVerificationToken"]);
    }
}

More info (a bit out of date now) here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!