You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6应用使用Google认证时出现关联失败错误

.NET Core 6 Google登录关联失败(Correlation failed)解决方案

问题概述

基于.NET Core 6构建的应用集成Google登录后,初期可正常登录,但一段时间后出现卡顿,日志显示关联Cookie丢失,报错:

RequestPath: /signin-google
'.AspNetCore.Correlation.Tqs1QKvDfDtMzN1758B177fdEvPXBxm0_NuiFaB1ySc' cookie not found.
RequestPath: /signin-google
An unhandled exception has occurred while executing the request.
Exception:
System.Exception: An error was encountered while handling the remote login.
---> System.Exception: Correlation failed.
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

已移除Program.cs中的SameSite规则,但问题仍未解决。

排查与解决步骤

1. 显式配置关联Cookie属性

移除全局SameSite规则后,需在Google认证配置中单独指定关联Cookie的核心属性,确保Cookie能被正确存储和读取:

builder.Services.AddAuthentication()
    .AddGoogle(options =>
    {
        options.ClientId = "你的Google ClientId";
        options.ClientSecret = "你的Google ClientSecret";
        
        // 配置关联Cookie
        options.CorrelationCookie.SameSite = SameSiteMode.Lax;
        // 生产环境强制HTTPS传输,本地开发可改为CookieSecurePolicy.None
        options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
        options.CorrelationCookie.HttpOnly = true;
    });

2. 延长关联Cookie过期时间

默认关联Cookie过期时间为15分钟,若用户跳转Google登录后停留过久,会导致Cookie过期失效。可适当延长过期时间:

options.CorrelationCookie.Expiration = TimeSpan.FromMinutes(30);

3. 适配反向代理/负载均衡环境

若应用部署在Nginx、IIS等反向代理后,需确保代理正确传递HTTPS协议头,否则ASP.NET Core会认为请求为HTTP,导致SecureCookie无法生效。在Program.cs中添加转发头配置:

var builder = WebApplication.CreateBuilder(args);

// 配置转发头
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor;
    // 生产环境替换为代理服务器真实IP
    options.KnownProxies.Add(IPAddress.Parse("127.0.0.1"));
});

var app = builder.Build();

// 必须在UseAuthentication之前调用
app.UseForwardedHeaders();

app.UseAuthentication();
app.UseAuthorization();

// 其他中间件配置...

4. 验证Google开发者控制台配置

确保Google开发者控制台中,OAuth 2.0 客户端ID的已授权的重定向 URI正确配置为:

  • 生产环境:https://你的域名/signin-google
  • 本地开发:http://localhost:端口号/signin-google

5. 清除浏览器缓存与Cookie

浏览器缓存的旧Cookie可能导致冲突,建议清除应用域名下的所有Cookie后重试登录流程。

内容的提问来源于stack exchange,提问作者Rasind Raveendran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 18:55:16