What is .AspNetCore.Antiforgery.xxxxxxx cookie in .Net Core?
Asked Answered
L

1

22

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?

Lakeshialakey answered 13/9, 2017 at 23:57 Comment(0)
U
32

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:

Univocal answered 14/9, 2017 at 5:29 Comment(1)
Or ... If Antiforgery is somehow already added by default, you can configure it in the way shown here: github.com/aspnet/Antiforgery/issues/97#issue-169311974Teddman

© 2022 - 2024 — McMap. All rights reserved.