使用负载均衡器时.NET Core 6应用Claims间歇性失效问题
问题分析与解决方案
切换到负载均衡环境后Claims时好时坏,核心原因基本是多服务器节点的会话/认证上下文不共享,结合你的.NET Core 6配置,给出以下针对性解决步骤:
统一所有节点的认证密钥
.NET Core默认会自动生成本地密钥,多服务器环境下必须手动指定共享密钥,否则不同节点无法解密彼此生成的认证Cookie。修改配置如下:.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { // 保留原有配置 o.LoginPath = new PathString("/Cadastro"); o.ExpireTimeSpan = TimeSpan.FromDays(1); o.SlidingExpiration = true; var defaultCallback = o.Events.OnRedirectToLogin; o.Events.OnRedirectToLogin = context => { context.RedirectUri = "/Login"; context.Response.Redirect(context.RedirectUri); return defaultCallback(context); }; // 添加密钥共享配置 // 推荐生产环境用共享网络目录存储密钥 o.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"\\shared-storage\auth-keys")); });若没有共享存储,也可以使用固定密钥(不推荐生产环境,存在密钥泄露风险),或用Azure Key Vault等密钥管理服务统一管理。
配置负载均衡器的粘性会话(临时过渡方案)
若暂时无法实现密钥共享,可先开启负载均衡器的会话亲和性,让同一用户的请求始终路由到同一台后端服务器。但此方案不适合服务器扩容或故障场景,仅作为临时过渡。修正Cookie作用域配置
确保Cookie的Domain和Path在所有节点一致,避免因作用域问题导致Cookie无法跨节点识别:.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { // 原有配置... o.Cookie.Domain = ".your-domain.com"; // 带前缀点,适配所有子域名 o.Cookie.Path = "/"; });同步服务器系统时间
开启SlidingExpiration后,若各节点系统时间偏差较大,会导致Cookie过期时间判断不一致,出现时有效时无效的情况,需确保所有后端服务器时间同步。处理负载均衡的SSL终止
若负载均衡器负责SSL终止,需配置后端服务器识别转发的协议头,避免Cookie的Secure属性失效:// 在Startup的Configure方法中添加 app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedProto }); // 同时修改Cookie配置 .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o => { // 原有配置... o.Cookie.SecurePolicy = CookieSecurePolicy.Always; // 仅HTTPS下传输Cookie });
内容的提问来源于stack exchange,提问作者Gleidson Guilherme
相关产品推荐
相关产品推荐

