.net core项目使用Cookie Authentication部署在windows iis上出现登录失效的解决方法
问题描述:.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
活着就要做有意义的事,最有意义的事就是好好活。