简体   繁体   中英

How to add prefix to cookie in asp.net core?

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?}");
            });
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM