.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
作者: Felix-Zhang
出处:https://www.cnblogs.com/zhangxiaoxia/p/12327442.html
版权:本站使用「CC BY 4.0」创作共享协议,转载请在文章明显位置注明作者及出处。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探