简体   繁体   English

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

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

I have a problem with an Asp.Net 5 application I'm currently developing.我目前正在开发的 Asp.Net 5 应用程序有问题。 Essentially it's an anonymous page with user-attached data, so I'm very much dependant on having a persistent and reliable cookie to identify a calling user.本质上它是一个带有用户附加数据的匿名页面,所以我非常依赖于拥有一个持久且可靠的 cookie 来识别调用用户。 Therefore, I have also checked how I need to configure cookies, and put them on a very long expiration timespan, and made them persistent.因此,我还检查了我需要如何配置 cookies,并将它们置于非常长的过期时间跨度上,并使它们持久化。

Here is my code:这是我的代码:

In my Startup.cs:在我的 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"];
        });

Obviously I also included the required calls in the Configure method:显然,我还在Configure方法中包含了所需的调用:

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

In the controller for setting the cookie, I'm using the following code:在用于设置 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,
    }
);

Where am I going wrong here?我在哪里错了? This seems to occur after every rebuild.这似乎发生在每次重建之后。

Thanks to Roar S.'s comment which pointed me in the right direction, I was able to figure out the problem:感谢 Roar S. 的评论为我指明了正确的方向,我能够找出问题所在:

The key point - my application is running in a container, which is restarted on rebuild.关键点 - 我的应用程序在一个容器中运行,该容器在重建时重新启动。 The culprit is indeed the data protection section - All cookie encryption keys stored on the machine are also regenerated when the container restarts.罪魁祸首确实是数据保护部分——当容器重新启动时,机器上存储的所有 cookie 加密密钥也会重新生成。

Therefore it is required to setup the.AddDataProtection section to either use a cloud-based storage, or a simple file mount for local development.因此,需要设置 .AddDataProtection 部分以使用基于云的存储,或用于本地开发的简单文件挂载。

This is what I ended up using:这就是我最终使用的:

In my docker-compose file, I added a mount:在我的 docker-compose 文件中,我添加了一个挂载:

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

And in my startup script:在我的启动脚本中:

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

Now the cookies are stable.现在 cookies 已经稳定了。

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

相关问题 如何使 ASP.NET Core 中的身份验证 cookie 无效? - How do I invalidate an authentication cookie in ASP.NET Core? 如何在ASP.net Core应用程序中同时使用Bearer和Cookie身份验证? - How can I use both Bearer and Cookie authentication in my ASP.net Core application? 如何在asp.net core 2.2中实现Cookie基本身份验证和jwt? - How can i implement Cookie base authentication and jwt in asp.net core 2.2? 在 Web 部署发布到远程 IIS 后,ASP.NET Core 3.1 身份持久化 cookie 身份验证仍然失败 - ASP.NET Core 3.1 identity persist cookie authentication after web deploy publish to remote IIS still fails 身份验证后,如何在ASP.Net Core中由OpenIdConnect中间件生成的身份验证cookie中添加自定义声明? - How do I add a custom claim to authentication cookie generated by OpenIdConnect middleware in ASP.Net Core after authentication? ASP.NET身份验证Cookie - ASP.NET Authentication cookie 如何删除此Cookie? ASP.NET MVC - How can I delete this cookie? ASP.NET MVC 如何停止ASP.net将.dll标记为只读,然后在重建时引发错误? - How can I stop ASP.net from marking .dll's read only then throwing errors on rebuild? 如何为我的 asp.net MVC 站点的每个访问者添加 cookie? - How do I add a cookie for every visitor to my asp.net MVC site? 如何在ASP.Net中延长表单身份验证时间? - How can I extend the Forms Authentication time in ASP.Net?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM