問題描述:.net core項目使用Cookie Authentication部署在windows iis,登錄時保存用戶信息在Cookie中,登錄一段時間后,登錄失效后需重新登錄。
版本.net core 3.0
問題分析:
理論上Cookie是保存在設備本地,有效期為1個月,與以前傳統的登錄方式基本一樣,但登錄上去后過一段時間登錄信息就沒了,就會跳轉重新登錄。
推測是在.net core中,登錄后登錄狀態在內存中,過一段時間后內存釋放了,導致登錄失效。
原始配置信息如下:
Startup:
public void ConfigureServices(IServiceCollection services) { //注冊Cookie認證服務 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.AccessDeniedPath = "/Home/Index"; options.LoginPath = "/Account/Login"; options.Cookie.Name = "TestMobile"; options.Cookie.SameSite = SameSiteMode.None; //不在此處設置Cookie有效期,在登錄時寫入User時設置 }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(builder => { builder.MapControllers(); builder.MapDefaultControllerRoute(); }); }
Controller
[Authorize] public ActionResult Index() { return View() }
登錄時保存用戶信息到Cookie:
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(JwtClaimTypes.Name, user.UserName)); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMonths(1), });
解決方案:
在其他參數都配置好的情況,增加ASP.NET Core中的密鑰保存程序,這樣配置好之后,就會持久化保存用戶登錄狀態等信息
密鑰保存有多種方式,我自己采用的是文件系統保存。
public Startup(IConfiguration configuration,
IWebHostEnvironment webHostEnvironment)
{
Configuration = configuration; WebHostEnvironment = webHostEnvironment; } public IConfiguration Configuration { get; } public IWebHostEnvironment WebHostEnvironment { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //基於文件系統的密鑰存儲庫(持久性保持密鑰) services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo($@"{WebHostEnvironment.ContentRootPath}\login-keys\")); }
官方文檔:
在 ASP.NET Core 中的密鑰存儲提供程序
https://docs.microsoft.com/zh-cn/aspnet/core/security/data-protection/implementation/key-storage-providers?view=aspnetcore-2.2&tabs=visual-studio