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
You can set a different name in your Startup.ConfigureServices
as in:
services.AddAntiforgery(opts => opts.CookieName = "MyAntiforgeryCookie");
For .Net Core 2.0.0 or greater there will be changes:
Reference: https://docs.microsoft.com/en-us/dotnet/api/Microsoft.AspNetCore.Antiforgery.AntiforgeryOptions?view=aspnetcore-2.0
For that use following:
services.AddAntiforgery(opts => opts.Cookie.Name = "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:
IAntiforgery
var tokenSet = antiforgery.GetAndStoreTokens(httpContext);
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.
The aim is for POST/PUT/DELETE/PATCH requests to include 2 things:
So the antiforgery middleware can validate there was no XSRF.
Update about cookie name/domain
The sensible default is for each application to have its own cookie. You mostly get that with the default approach as no domain is specifically set on the cookie, so the cookie takes the domain from the request. That would mean different cookies for different applications unless the appliacations are hosted with the same domain.
You might only want to share the cookie in special cases, for example if you have 2 applications where a form in app A posts to app B. In those cases make sure you use a domain/subdomain that matches both applications and both use the same cookiea name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With