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

Docker部署ASP.NET Core 8 Razor Pages谷歌认证重定向URI不匹配求助

问题排查与解决方案

核心原因

ASP.NET Core 默认不信任反向代理发送的 X-Forwarded-Proto 等转发头,即便添加了 UseForwardedHeaders 中间件,若未配置信任的代理地址,应用仍会使用容器内部的HTTP协议生成redirect_uri,导致谷歌认证出现redirect_uri_mismatch错误。

解决方案步骤

1. 修正ForwardedHeaders中间件配置

修改ForwardedHeaders配置,添加信任的代理IP或网络段(比如Nginx所在主机IP、Docker内部子网),同时确保中间件顺序在UseAuthentication之前:

// Program.cs中,放在builder.Build()之后、app.UseAuthentication()之前
var forwardedHeadersOptions = new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
    // 添加Nginx主机IP,替换为实际地址
    KnownProxies = { IPAddress.Parse("192.168.1.100") },
    // 若不确定具体IP,可信任整个Docker私有子网
    // KnownNetworks = { new IPNetwork(IPAddress.Parse("172.17.0.0"), 16) }
};

app.UseForwardedHeaders(forwardedHeadersOptions);

// 后续再启用认证中间件
app.UseAuthentication();
app.UseAuthorization();

2. 验证Nginx反向代理头传递

确保Nginx在转发请求时正确传递X-Forwarded-Proto和X-Forwarded-For头,修改server配置块:

server {
    listen 443 ssl;
    server_name example.com;

    # SSL相关配置省略

    location / {
        proxy_pass http://localhost:xxxx; # 替换为你的Docker容器端口
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme; # 关键:传递真实的HTTPS协议
    }
}

3. 检查谷歌开发者控制台的重定向URI配置

在谷歌API控制台的OAuth 2.0客户端ID设置中,确认已添加https://example.com/signin-google作为授权重定向URI,线上环境需确保仅启用HTTPS版本的URI。

4. 手动指定谷歌认证回调地址(可选)

若上述配置生效后仍有问题,可手动强制回调地址为HTTPS:

.AddGoogle(options =>
{
    options.ClientId = "myClientId";
    options.ClientSecret = "myClientSecret";
    options.SaveTokens = true;
    options.CallbackPath = new PathString("/signin-google");
    options.Events.OnRedirectToAuthorizationEndpoint = context =>
    {
        // 强制转换为HTTPS地址
        var uriBuilder = new UriBuilder(context.RedirectUri) { Scheme = "https" };
        context.Response.Redirect(uriBuilder.ToString() + "&prompt=consent");
        return Task.CompletedTask;
    };
});

内容的提问来源于stack exchange,提问作者Pouya Samie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:02:45