首页 > 解决方案 > 如何在 asp.net core 中为 cookie 添加前缀?

问题描述

我在 SecurityHeaders.com 上运行了扫描,它显示 cookie 没有前缀并且我不知道如何向 cookie 添加前缀的警告。谁能告诉我如何在 asp.net core 中做到这一点?网站扫描结果截图

这是 Startup.cs 类中的 ConfigureServices 方法

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

这是配置方法

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

标签: c#asp.net-corecookiessetcookie

解决方案


我找到了答案。因此,如果有人需要,请在此处发布。在 SessionOptions 中,将 Cookie.Name 设置为 prefix+name。

__Secure-下面是会话 Cookie 名称中的前缀。

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

是的,它也解决了扫描中的安全标头问题。


推荐阅读