簡體   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