简体   繁体   中英

How to enable HttpOnly cookies on ASP.NET Core 2.1 Web site

I have created a standard ASP.NET Core MVC website with Core 2.1 in Visual Studio using File->New Project.

In the Startup.cs is the boilerplate code

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

When I browse the site there is a single.AspNet.Consent cookie when I accept the cookiepolicy. It is marked by default secure but not httponly.

How to I enable HttpOnly on ALL cookies?

Thanks.

Have you tried this?

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

});

The consent cookie is not HttpOnly because it is set client side via JavaScript. You can find the code in the _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>

If you need an HttpOnly cookie you should implement the consent logic yourself in middleware or a controller and use a regular form with a POST-request for example.

When setting a cookie manually (eg against an HTTPContext), there is an easy CookieOptions object that you can use to set HttpOnly to true. It ends up looking a bit like this :

HttpContext.Response.Cookies.Append(
"CookieKey",
"CookieValue",
new CookieOptions
{
    HttpOnly = true
});

Microsoft have a middleware that uses cookies for Authentication. If you were to use it in your app, you add it in the Configure method of your startup.cs.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvc();
    app.UseCookieAuthentication();
}

If you are using CookieAuthentication in this way, HttpOnly cookies will be used by default. For more details,refer to here

It looks as though you can do this in Startup.cs using the IApplicationBuilder.UseCookePolicy:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       ...
     
        app.UseCookiePolicy(
            new CookiePolicyOptions
            {
                Secure = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always,
                HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always
            });
}

https://learn.microsoft.com/en-us/do.net/api/microsoft.as.netcore.builder.cookiepolicyoptions.httponly?view=as.netcore-2.1

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