Jonas Axelsson Jonas Axelsson - 1 month ago 17
ASP.NET (C#) Question

Using the antiforgery cookie in ASP.NET Core but with a non-default CookieName

I'm thinking about changing name of the default antiforgery cookie in ASP.NET Core.

The reason why I would like to change the cookie name is to anonymize the cookie, in my opinion there is no reason why end users should be able to determine the responsibility of this cookie.

Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions.CookieName


  1. How do I change the name of the antiforgery cookie? I guess it should be done in the Startup.cs file in somehow?

  2. What possible implications could occur by changing name the default antiforgery cookie?

  3. How do I use the antiforgery cookie in ASP.NET Core?


Answer

You can set a different name in your Startup.ConfigureServices as in:

services.AddAntiforgery(opts => opts.CookieName = "MyAntiforgeryCookie");

By default AddMvc() internally calls AddAntiforgery(), which means you get the default cookie, header and form names. If you need to/want to use different names, you can do so by manually calling AddAntiforgery as above.

There should be no implications for your application if you change the cookie name (unless you added code yourself that manually used that cookie). You might also want to change the header/form name, for example the offical Antiforgery repo has an example that uses Angular and changes the header as the standard angular XSRF token header.

In order to use it, add the [ValidateAntiForgeryToken] to controller actions other than GET requests.

You have to do nothing else for standard html forms as long as you use the asp form tag helpers, see this question.

If you use ajax requests, then you will need to include either a header or a field within your request that includes the generated token. You basically need to:

  1. Get an IAntiforgery
  2. Call var tokenSet = antiforgery.GetAndStoreTokens(httpContext);
  3. Make it available to your js code so it knows about the value tokenSet.RequestToken to be included as either a field with name tokenSet.FormFieldName or a header with name tokenSet.HeaderName within each ajax request. (rendering the token into a JS object inside a script section in your js layout, add a JS readable cookie as in the angular example, keep rendering hidden fields you include within the ajax request, ...)

The aim is for POST/PUT/DELETE/PATCH requests to include 2 things:

  • the antiforgery cookie
  • the field/header with the token

So the antiforgery middleware can validate there was no XSRF.