How to set Partitioned attribute for all cookies in ASP.NET Core?

501 Views Asked by At

As part of adapting to the phase-out of third-party cookies, we would like to adopt Cookies Having Independent Partitioned State (CHIPS) across our whole application. How can we easily set the new Partitioned attribute for all cookies?

1

There are 1 best solutions below

1
Jacob Bundgaard On

We can use the CookiePolicyMiddleware to add the Partitioned attribute to all appropriate cookies (those with the Secure and SameSite=None attributes):

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.OnAppendCookie = context =>
        {
            if (context.CookieOptions.Secure && context.CookieOptions.SameSite == SameSiteMode.None)
            {
                context.CookieOptions.Extensions.Add("Partitioned");
            }
        };
    });
}

public void Configure(IApplicationBuilder application, IHostEnvironment env)
{
    application.UseCookiePolicy();
}