c# - 每次重建后都会重置 Asp.Net 5 身份验证 cookie - 我怎样才能真正坚持下去?
问题描述
我目前正在开发的 Asp.Net 5 应用程序有问题。本质上它是一个带有用户附加数据的匿名页面,所以我非常依赖于拥有一个持久且可靠的 cookie 来识别调用用户。因此,我还检查了我需要如何配置 cookie,并将它们置于非常长的过期时间跨度上,并使它们持久化。
这是我的代码:
在我的 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 的控制器中,我使用以下代码:
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是稳定的。
推荐阅读
- pandas - pandas中迭代函数的值
- angularjs - 离子错误:不幸的是应用程序已停止
- wpf - SelectedIndex 不通过双击更新 WPF TabControl,但在按下按钮时更新
- css - CSS Counter 在 Chrome 中使用 slidetoggle 给出错误的编号
- c# - UWP 应用程序 - 如何将响应列表保存到文件中并取回数据
- c# - Func<> 动态添加一个额外的参数
- html - 使用 AngularJS 弹出直方图窗口
- javascript - 使用 socket.io 接收事件并更新元素 html
- php - Preg_matching 电子邮件并查找特定文本
- javascript - 使用JS更改输入字段的背景颜色