【问题标题】:How to add prefix to cookie in asp.net core?如何在 asp.net core 中为 cookie 添加前缀?
【发布时间】:2021-12-16 18:48:26
【问题描述】:

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

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

【问题讨论】:

  • 你是如何设置cookie的?
  • 我正在使用 cookiepolicyoptions 从启动类中的 configureservices 方法配置它,然后在 configure 方法中添加 usecookiepolicy。
  • 请包含该代码。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: c# asp.net-core cookies setcookie


【解决方案1】:

我找到了答案。因此,如果有人需要,请在此处发布。 在 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;
            });

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

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2017-06-10
    • 2019-10-21
    相关资源
    最近更新 更多