Kentico 12 MVC Anti-Forgery Token and Output Caching

Michael John Veloso asked on December 4, 2019 20:38

Hi,

We are currently have a Kentico 12 MVC project which is hosted in a Web Farm.

We are also using output caching to improve performance.

But recently we are experience an issue with Anti-Forgery Token validation (@Html.AntiForgery()). And this form are not a Form Widget. And we are using ajax to post the form.

<form id="formtoken" action="/" method="post">
    @Html.AntiForgery()
</form>

$.ajax({
   url: urlPost,
   type: 'POST',
   data: { _RequestVerificationToken: $('body').find('input[name=__RequestVerificationToken]:first').val()
   },
   success: function success(obj) {
        alert(object.Message);
   }
});

We assumed that this is because of the output cache and that the anti-forgery token is part of the output cache data and also think that when the cookie expires this token that is cached is no longer valid.

And I have read about the Kentico HtmlHelperExtions that has a method AntiForgery() which ensures the token for cached request.

@Kentico.Web.Mvc.HtmlHelperExtensions.Kentico(Html).AntiForgeryToken()

Have anyone tried this and could this help resolve the issue that we are encountering.

Thank you very much in advance.

Recent Answers


Michal Samuhel answered on December 5, 2019 10:05

Most likely you are correct and HTML token is being saved within output cache. AntiForgeryToken is not Kentico proprietary, but it is using standard .NET implementation. You could as well get to it by plain HTML.AntiForgeryToken(). So this is something that would happen across the board on any .NET application

I will quote an answer from stackoverflow post " Caching nicely caches the answer, including the value of the AntiForgeryToken. Disable caching on forms, and in particular on pages that use AntiForgeryToken. If you think about this further, if you're in a data-entry app, do you want to cache your data-entry forms? Probably not. However you do want to cache heavy reports -- even if it's just micro-caching -- a second or two."

For your use case, I would rather suggest using CORS header as a protection. You are submitting AJAX request from your web site to your web site so this request should be accepted only from single source domain. Yours. This way you can prevent forged request coming from outside parties. It can be done on IIS or via various packages.

This article covers more on token usage and possible pitfalls.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.