Does it make sense to put antiforgerytoken in _Layout.cshtml?

Does it make sense to put antiforgerytoken in _Layout.cshtml?

问题

I'm developing an ASP.NET MVC application and I'm planing to protect each non GET request (POST, PUT, DELETE, etc...) with AntiForegeryToken.

I've implemented an extension of the classical AntiForgery verification based on the [__RequestVerificationToken] sent in the header. This because most of my calls are async ($.ajax()) and it turns out easier for me to send the hidden field value that way.

Does it make sense to put one single @Html.AntiForgeryToken() in the _Layout.cshtml (template for all pages) and always refer to that one only ?

I've tryed to understand what wolud be different beteen this option and putting it in each form (that I don't use much since my requests are pretty much all async), but I haven't.

Can anyone clear this to me ?

Thanks

Lorenzo

 

回答

You can put it in your _Layout.cshtml and generate a single token when the page is rendered, that's fine.

While there is a very slight security benefit of using a different token for every request, if your token has enough entropy (and the standard token generated by @Html.AntiForgeryToken() does), then it is practically infeasible for an attacker to guess the token even during the time of a user session. So one token per user session is still considered secure in most cases.

Actually, trying to use a new token for each request leads to all kinds of bugs in a Javascript heavy application, because the browser needs a non-neglectible time to actually change things like a cookie value or to send a request, and frequent ajax requests will lead to a race condition and you will have hard to debug bugs around token mismatches.

ASP.NET MVC still focuses on traditional form-based applications in this regard, and while you can use it to prevent CSRF in modern Javascript-heavy apps with some tweaks (like a custom attribute to actually verify a token sent in request headers), you do have to write some custom code to do that. Hopefully Microsoft will add built in support in future versions.

UPDATE

After implementing the solution with @Html.AntiForgeryToken() directly in Template page (_Layout.cshtml) I found out a possible problem bound to the use of custom Claims. The problem happens during re-validation of UserIdentity. As a reference I'll leave the link to another post in which I've been dealing with that and added there the wotrkaround for those who choose the same implementation. Custom Claims lost on Identity re validation

Hope it helps !

 

 

 

 

posted @ 2021-09-24 16:09  ChuckLu  阅读(52)  评论(0编辑  收藏  举报