Search code examples
c#.netasp.net-core.net-coreantiforgerytoken

What is .AspNetCore.Antiforgery.xxxxxxx cookie in .Net Core?


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?


Solution

  • 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: