[英]How to enable HttpOnly cookies on ASP.NET Core 2.1 Web site
我使用 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 时,会有一个 single.AspNet.Consent cookie。 它默认标记为安全但不是 httponly。
如何在所有 cookies 上启用 HttpOnly?
谢谢。
你试过这个吗?
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
});
同意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请求的常规表单。
手动设置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 cookie 。 有关更多详细信息,请参阅此处
看起来您可以在 Startup.cs 中使用 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
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.