Search code examples
c#asp.net-corecookieschips

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


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?


Solution

  • 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();
    }