9

I'm stuck at the moment trying to figure out how can I send the antiforgery token using Dropzone.js and vanilla javascript (no jQuery).

This is my initialization code at the moment:

$(document).ready(function (e) {
        var myDropzone = new Dropzone("#myDropzone", { url: "/Media/AjaxUpload", maxFilesize: 10, addRemoveLinks: true, maxFiles: 1 });
        myDropzone.on("success", function (response) {
            //Do some personal stuff.
        });
        myDropzone.on("sending", function (xhr, formData) {
            formData["__RequestAntiForgeryToken"] = document.getElementsByName("__RequestVerificationToken")[1].value
        });

    });

I have tried appending the token to no avail on Dropzone's sending event, even at the header. Any suggestions on how to achieve this?

2 Answers 2

7

I think you nearly nailed it there on the first go, Jose. The small mistake you made was missing an argument in the event handler function.

From the Dropzone documentation:

Called just before each file is sent. Gets the xhr object and the formData objects as second and third parameters, so you can modify them (for example to add a CSRF token) or add additional data.

The event arguments are actually file, xhr, formData, and if you include all three then you can manipulate the form successfully. The advantage of doing things this way is that there is no need to create a custom attribute, just use the ValidateAntiForgeryToken attribute.

myDropzone.on("sending", function (file, xhr, formData) {
    formData["__RequestAntiForgeryToken"] = document.getElementsByName("__RequestVerificationToken")[1].value;
});

I have tested this with a slightly different implemetation than your's, and it works nicely.

3
  • 1
    For me using formData.append("__RequestAntiForgeryToken", tokenElement)also worked.
    – Pablo
    Feb 1, 2018 at 18:07
  • 1
    for me it works only with formData.append(k,v) not with formData[k]= v, and it has to be __RequestVerificationToken not __RequestAntiForgeryToken (asp.net core 3)
    – Omu
    Jan 17, 2020 at 19:48
  • formData.append("__RequestVerificationToken") works nicely, I needed to to use |document.getElementsByName("__RequestVerificationToken")[0].defaultValue on the client to get the token Oct 16 at 15:58
6

The way I ended up achieving this was through many suggestions at Stackoverflow. I created a special filter on MVC and passed the token via the headers. Like this:

Taking the idea from here: http://johan.driessen.se/posts/Updated-Anti-XSRF-Validation-for-ASP.NET-MVC-4-RC

I managed to send the token via dropzone's header:

The code ended up like this:

var myDropzone = new Dropzone("#myDropzone", {
            url: "/Media/AjaxUpload", maxFilesize: 10, addRemoveLinks: true, maxFiles: 1,
            headers: { "__RequestVerificationToken": document.getElementsByName("__RequestVerificationToken")[1].value }
        });

I added "headers" to the Dropzone instantiation, and added the filter to MVC:

  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple= false, Inherited = false)]
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"]);
    }
}

Then apply to your controller:

 [ValidateJsonAntiForgeryToken]
    public JsonResult AjaxUpload(HttpPostedFileBase file)
    {
        //Do Logic here!

        return Json("Success");
}
3
  • 1
    Dude, this is golden! A rare treasure indeed. Well done.
    – pjdupreez
    May 8, 2018 at 13:20
  • I'm finding that dropzone is setting __RequestVerificationToken to lowercase in the headers payload and MVC is failing. Very strange... Dec 4, 2019 at 15:08
  • 1
    Yep seen the same with latest dropzone, dropped it in favor of other development on the site. But getting to a beta release and I need to revisit the implementation of antiforgery Oct 15 at 9:03

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.