21

I was trying to use ValidateAntiForgeryToken in .Net Core but I was getting .AspNetCore.Antiforgery.xxxxxxx cookie is missing.

What is this .AspNetCore.Antiforgery.xxxxxxx cookie?

Sharif Mamun
  • 3,508
  • 5
  • 32
  • 51

1 Answers1

31

ASP.NET Core looks for this cookie to find the X-CSRF token.

The ValidateAntiForgeryToken is an action filter that can be applied to an individual action, a controller, or globally for the app. Requests made to actions that have this filter applied will be blocked unless the request includes a valid antiforgery token.

In general ASP.NET Core may look for the token in cookie or header. So you may have the situation when

  • instead of cookie the header is used to pass token
  • cookie with token has the different name than the ASP.NET Core expected.

By default, the ASP.NET Core will generate and expect a unique cookie name beginning with the DefaultCookiePrefix (".AspNetCore.Antiforgery.").

This could be overriden using an antiforgery option CookieName:

services.AddAntiforgery(options => options.CookieName = "X-CSRF-TOKEN-COOKIENAME");

For .Net Core 2.0.0 or greater there will be changes:

Reference: https://learn.microsoft.com/en-us/dotnet/api/Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions?view=aspnetcore-2.0

For that use following:

services.AddAntiforgery(options => options.Cookie.Name = "X-CSRF-TOKEN-COOKIENAME");

If talking about header, name could be specified by:

services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

Look into:

Tim
  • 5,435
  • 7
  • 42
  • 62
Set
  • 47,577
  • 22
  • 132
  • 150
  • Or ... If `Antiforgery` is somehow already added by default, you can configure it in the way shown here: https://github.com/aspnet/Antiforgery/issues/97#issue-169311974 – olfek Sep 29 '19 at 19:44