ASP.NET Core MVC anti forgery

Viewed 5560

Trying to turn on anti forgery in core mvc project but with no luck. What was done:

Filter added to automatically check anti forgery token on every POST request.

services.AddMvc(o =>
{
  o.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});

Token generation was added to each page this way.

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery;
@{
   var antiforgeryRequestToken = Antiforgery.GetAndStoreTokens(Context).RequestToken;
}
...
...
<script>
    var antiforgeryToken = @Json.Serialize(antiforgeryRequestToken);
</script>

And finally each client ajax request adds RequestVerificationToken this way.

var options = {
        url: o.url, type: 'POST', data: o.params, headers: { 'RequestVerificationToken': antiforgeryToken } };

I can see each ajax request has the token but I am always getting 400 for any POST request. If I disable the filter, it works fine. But once I enable it, asp.net core starts verification on each POST request and it always returns me 400.

Any ideas?

UPDATE:

I've followed the instructions I got in the comments and now the code looks like following. ConfigureServices method:

services.AddMvc(o => { 
  o.Filters.Add(new HandleAllExceptionsFilterFactory()); 
  o.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); 
}); 

services.AddAntiforgery(o => o.CookieName = "XSRF-TOKEN");

And here is the middleware registered:

app.Use(next => context => { 
if (context.Request.Path == "/") 
{ 
    var antiforgery = app.ApplicationServices.GetService<IAntiforgery>(); 
    var token = antiforgery.GetAndStoreTokens(context); 
    context.Response.Cookies.Append("XSRF-TOKEN", token.RequestToken, new CookieOptions {HttpOnly = false}); 
} 

return next(context); 
});

I also removed any client side javascript code that has been sending the header before. But it still doesn't work.

2 Answers
Related