ASP.NET Core MVC:設置身份 cookie 過期
在我的 ASP.NET Core MVC 應用程序中,身份驗證 cookie 的生命週期設置為“會話”,因此它會持續到我關閉瀏覽器。我使用 MVC 的預設身份驗證方案:
app.UseIdentity();如何延長 cookie 的生命週期?
您正在使用的 ASP.NET 身份中間件是一些呼叫的包裝器,
UseCookieAuthentication其中包括管道上的 Cookie 身份驗證中間件。這可以在 GitHub 上的 Identity 中間件的建構器擴展的原始碼中看到。在這種情況下,配置底層 Cookie 身份驗證應該如何工作所需的選項被封裝在IdentityOptions設置依賴注入時配置。確實,查看我連結到您的原始碼可以看到,當您呼叫時會執行以下內容
app.UseIdentity():var options = app.ApplicationServices.GetRequiredService<IOptions<IdentityOptions>().Value; app.UseCookieAuthentication(options.Cookies.ExternalCookie); app.UseCookieAuthentication(options.Cookies.TwoFactorRememberMeCookie); app.UseCookieAuthentication(options.Cookies.TwoFactorUserIdCookie); app.UseCookieAuthentication(options.Cookies.ApplicationCookie); return app;為了設置
IdentityOptions類,該AddIdentity<TUser, TRole>方法有一個重載版本,它允許使用一個 lambda 配置選項。因此,您只需要傳入一個 lambda 來配置選項。在這種情況下,您只需訪問Cookies選項類的屬性並ApplicationCookie根據需要進行配置。要更改時間跨度,您可以執行以下操作services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(1); });**編輯:**只有在呼叫時我們傳入一個with set to的實例
ExpireTimeSpan時才使用該屬性。HttpContext.Authentication.SignInAsync``AuthenticationProperties``IsPersistent``true僅使用 Cookie 身份驗證中間件進行嘗試,結果證明這是有效的:如果我們只是在沒有此選項的情況下登錄,我們會得到一個持續會話的 cookie,如果我們將它一起發送,我們會得到一個持續配置時設置的 cookie中間件。
使用 ASP.NET Identity 的方法是傳遞帶有值
isPersistent的參數。這最終是對設置為 true的傳遞的呼叫。電話最終是這樣的:PasswordSignInAsync``true``SignInAsync``HttpContext``AuthenticationProperties``IsPersistentvar result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
RememberMe如果我們設置IsPersistent為 true 或 false ,則配置在哪裡。