Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change default cookie names in ASP.NET Core MVC

I would like to change the default Cookie name for .AspNetCore.Antiforgery.xxx in asp.mvc core 3.X however I do not seem to find any documentation on it. is it even possible?

The only one I found to be able to alter was this:

services.Configure<CookiePolicyOptions>(options =>
{
  options.CheckConsentNeeded = context => true;
  options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
  options.ConsentCookie.Name = "GDRP";
});
like image 319
Walter Verhoeven Avatar asked Jan 01 '20 17:01

Walter Verhoeven


Video Answer


3 Answers

This is achievable using AddAntiforgery. Here's an example taken from the docs and modified accordingly:

services.AddAntiforgery(options => 
{
    options.Cookie.Name = "YourCookieName";
});

There's a useful page in the docs that lists the built-in ASP.NET Core cookies and where the configuration for each comes from.

like image 121
Kirk Larkin Avatar answered Oct 24 '22 03:10

Kirk Larkin


For .NET 5.0 and higher

in ProjectRoot/Startup.cs class

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.Cookie.Name = "your_cookie_name";
        });
    // ...
    services.AddControllers();
}
like image 4
mikolaj semeniuk Avatar answered Oct 24 '22 05:10

mikolaj semeniuk


ok, found it already, for those that are looking

services.AddAntiforgery(options =>
{
     options.Cookie.Name = "my-x-name";
     options.HeaderName = "my-x-name";
});

It will accept any string, need to validate if it works or if something else needs to be updated...

like image 3
Walter Verhoeven Avatar answered Oct 24 '22 05:10

Walter Verhoeven