我使用File-> New Project在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?}");
});
}
当我浏览站点时,当我接受cookiepolicy时,只有一个.AspNet.Consent cookie。默认情况下,它被标记为安全,但不是httponly。
如何在所有cookie上启用HttpOnly?
谢谢。
答案 0 :(得分:1)
您尝试过吗?
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
});
答案 1 :(得分:0)
同意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>
如果您需要HttpOnly cookie,则应自己在中间件或控制器中实现同意逻辑,并使用带有POST请求的常规格式。
答案 2 :(得分:0)
手动设置Cookie(例如针对HTTPContext)时,有一个简单的CookieOptions对象,可用于将HttpOnly设置为true。最终看起来像这样:
HttpContext.Response.Cookies.Append(
"CookieKey",
"CookieValue",
new CookieOptions
{
HttpOnly = true
});
Microsoft有一个使用Cookie进行身份验证的中间件。如果要在应用程序中使用它,请在startup.cs的Configure方法中添加它。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
app.UseCookieAuthentication();
}
如果您以这种方式使用CookieAuthentication,则默认使用HttpOnly cookies。有关更多详细信息,请参阅here