1

I works on an Asp.net MVC 5 project and know there is 2 way to pass the AntiForgeryToken to the server in ajax calls:

  • Put it in Header
  • Put it in Data

I like putting AntiForgeryToken in request header and my codes works well both client and server side. I followed this article.

I put the AntiForgeryToken in each $.ajax call header and it works nice

But

Now i decided write new codes to add AntiForgeryToken to all Ajax calls that have POST type in my page globally and remove the header setting in each $.ajax block of codes.

Then i wrote this codes to implement my decision and it works well too when i have one form in my page (i did not test it in complected cases such as multiple forms in a page and...):

var antiForgerytoken = $('input[name="__RequestVerificationToken"]').val();

$.ajaxPrefilter(function (options, originalOptions, jqXhr) {
    if (options.type.toUpperCase() == "POST") {
        jqXhr.setRequestHeader("__RequestVerificationToken", antiForgerytoken);
    }
});

My questions:

  1. Has this decision any security or inappropriate side effect?
  2. When i have several form in my page that each one created by a different partial view and will handle by different actions in different controllers should i find the related AntiForgeryToken in each form and inject it to all Ajax calls that are related to that form? Or just above codes is enough?

Maybe base of this question is another question that wrote here and @DarinDimitrov answered it include this description:

ASP.NET MVC will simply reuse the same value for all forms so it doesn't need to know which form sent the request in order to validate it

Is this rule is absolute? do you know any reference? I saw some opposite view in comments of @DarinDimitrov answer

  1. If i should behavior with each form AntiForgeryToken separately, how should i change the above codes to set AntiForgeryToken in Ajax header globally to work with all forms that rendered in a MVC page?
Community
  • 1
  • 1
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98

0 Answers0