繁体   English   中英

每次重建后都会重置 Asp.Net 5 身份验证 cookie - 我怎样才能真正坚持下去?

[英]Asp.Net 5 Authentication cookie is reset after every rebuild - How can I truly persist it?

我目前正在开发的 Asp.Net 5 应用程序有问题。 本质上它是一个带有用户附加数据的匿名页面,所以我非常依赖于拥有一个持久且可靠的 cookie 来识别调用用户。 因此,我还检查了我需要如何配置 cookies,并将它们置于非常长的过期时间跨度上,并使它们持久化。

这是我的代码:

在我的 Startup.cs 中:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.Events.OnRedirectToLogin = context =>
            {
                context.Response.StatusCode = 401;
                return Task.CompletedTask;
            };

            options.ExpireTimeSpan = TimeSpan.FromDays(100 * 365);
            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.Cookie.MaxAge = TimeSpan.FromDays(100 * 365);
            options.Cookie.SameSite = _webHostEnvironment.IsDevelopment() ? SameSiteMode.None : SameSiteMode.Strict;
            options.Cookie.Name = Configuration["IdentificationCookieName"];
        });

显然,我还在Configure方法中包含了所需的调用:

app.UseAuthentication();
app.UseAuthorization();

在用于设置 cookie 的 controller 中,我使用以下代码:

var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, callerId.ToString()));

var principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    principal,
    new AuthenticationProperties()
    {
          IsPersistent = true,
          ExpiresUtc = DateTime.UtcNow.AddYears(100),
          AllowRefresh = true,
    }
);

我在哪里错了? 这似乎发生在每次重建之后。

感谢 Roar S. 的评论为我指明了正确的方向,我能够找出问题所在:

关键点 - 我的应用程序在一个容器中运行,该容器在重建时重新启动。 罪魁祸首确实是数据保护部分——当容器重新启动时,机器上存储的所有 cookie 加密密钥也会重新生成。

因此,需要设置 .AddDataProtection 部分以使用基于云的存储,或用于本地开发的简单文件挂载。

这就是我最终使用的:

在我的 docker-compose 文件中,我添加了一个挂载:

volumes:
  - ./Keys/Storage:/keys/storage

在我的启动脚本中:

if (IsDevelopmentEnvironment())
{
     services.AddDataProtection()
         .PersistKeysToFileSystem(new DirectoryInfo("/keys/storage"));
}

现在 cookies 已经稳定了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM