如何在 ASP.NET Core 2.1 网站上启用 HttpOnly cookie

M R*_*ker 7 c# asp.net-core-mvc .net-core asp.net-core

我在 Visual Studio 中使用“文件”->“新建项目”使用 Core 2.1 创建了一个标准 ASP.NET Core MVC 网站。

Startup.cs 中是样板代码

 public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


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

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
Run Code Online (Sandbox Code Playgroud)

当我浏览该网站时,当我接受 cookiepolicy 时,会出现一个 .AspNet.Consent cookie。默认情况下,它被标记为安全的,但不是 httponly。

如何在所有 cookie 上启用 HttpOnly?

谢谢。

Tan*_*jel 5

你试过这个吗?

services.ConfigureApplicationCookie(options =>
{
    // Cookie settings
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(10);

});
Run Code Online (Sandbox Code Playgroud)


Hen*_*ema 2

同意 cookie 不是 HttpOnly,因为它是通过 JavaScript 在客户端设置的。您可以在以下位置找到代码_CookieConsentPartial.cshtml

<script>
    (function () {
        var button = document.querySelector("#cookieConsent button[data-cookie-string]");
        button.addEventListener("click", function (event) {
            document.cookie = button.dataset.cookieString;
        }, false);
    })();
</script>
Run Code Online (Sandbox Code Playgroud)

如果您需要 HttpOnly cookie,您应该自己在中间件或控制器中实现同意逻辑,并使用带有 POST 请求的常规表单。