Home > Mobile >  How to add prefix to cookie in asp.net core?
How to add prefix to cookie in asp.net core?

Time:11-05

I have run a scan on SecurityHeaders.com which shows a warning that cookie has no prefix and I don't know how to add a prefix to a cookie. Can anybody tell me how to do it in asp.net core ?. Screenshot of website scan result

Here is the ConfigureServices method from Startup.cs class

public void ConfigureServices(IServiceCollection services)
        {
            
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.Secure = CookieSecurePolicy.Always;
            });

            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
               .AddAzureAdB2C(options => Configuration.Bind("AzureAdB2C", options))
               .AddCookie(); 

            services.AddMvc()
               .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDistributedMemoryCache();
            services.AddSession();
       }

And here is Configure method

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            app.UseExceptionHandler("/Error");
            app.UseHsts();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute("home", "{action=Index}",
                    defaults: new { controller = "Home" });
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

CodePudding user response:

I've found the answer. So posting it here if anybody needs it. Within the SessionOptions, set Cookie.Name to prefix name.

Below __Secure- is prefix in Session Cookie Name.

services.AddSession(options =>
            {
                options.Cookie.Name = "__Secure-.AspNetCore.Session";
                //options.IdleTimeout = TimeSpan.FromSeconds(600);
                //options.Cookie.IsEssential = true;
            });

and yes it solves the security header issue in scan too.

  • Related