如何在.net core 2.0中配置httponly和secure标志?

时间:2018-03-19 12:05:58

标签: .net authentication asp.net-core cookie-httponly

没有错误但是我无法在浏览器中配置httponly状态。 你能查一下我的代码吗?

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();
        services.AddMvc();
        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromMinutes(20);
            options.Cookie.HttpOnly = true;
            options.Cookie.SameSite = SameSiteMode.Strict;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
          });
      }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       app.UseSession();
        app.UseStaticFiles();

        app.UseCookiePolicy(new CookiePolicyOptions
        {
            HttpOnly = HttpOnlyPolicy.Always,
            Secure =CookieSecurePolicy.Always,
            MinimumSameSitePolicy=SameSiteMode.None
        });
      }

2 个答案:

答案 0 :(得分:1)

在ASP.NET Core 2.X中,您可以使用以下代码:

public void ConfigureServices(IServiceCollection services)
{
     // This can be removed after https://github.com/aspnet/IISIntegration/issues/371
     services.AddAuthentication(
        options =>
        {
             //Blah Blah Blah
         }).AddCookie(opts =>
         {
              opts.Cookie.HttpOnly = false;
          });
 }

 public void Configure(IApplicationBuilder app)
 {
     app.UseAuthentication();
 }

请注意,这已从ASP.NET Core 1.X更改

答案 1 :(得分:0)

根据文档(https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x),您可以通过IApplicationBuilder.UseCookiePolicy()配置HttpOnly:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    /*..*/
    app.UseStaticFiles();
    app.UseSession();
    app.UseCookiePolicy(new CookiePolicyOptions
    {
        HttpOnly = HttpOnlyPolicy.Always
    });
}