ASP.NET 在反向代理后面使用 Azure AD 身份验证的核心应用设置错误 redirect_uri

ASP.NET Core app with Azure AD authentication behind a reverse proxy is setting the wrong redirect_uri

我已经为此苦苦思索了一段时间。 我在 Azure 应用服务上有一个 ASP.NET Core 3.1 Web 应用程序 运行。 Web 应用程序具有 Azure AD 身份验证设置,转发 headers。 这是 ConfigureService:

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

services
    .AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options =>
    {
        Configuration.Bind("AzureAd", options);
    });

这里是 Configure:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseForwardedHeaders();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseForwardedHeaders();
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseRouting();
app.UseCors(Configuration["AllowedHosts"]);
app.UseAuthentication();
app.UseAuthorization();

我正在使用 Azure 应用程序网关作为反向代理。 身份验证流程出现问题。身份验证后,URL 中提供的 redirect_uri 是 *.azurewebsites.net 地址,而不是我在 App Gateway *.mydomain.com 中配置的地址。进一步调查显示以下 headers 在请求中提供给应用服务:

X-FORWARDED-PROTO: https
X-FORWARDED-PORT: 443
X-Forwarded-For: ***IP ADDR OF APP GATEWAY***
X-Original-URL: ***
X-ORIGINAL-HOST: *.mydomain.com
X-ARR-SSL: 2048|256|C=US, S=Washington, L=Redmond, O=Microsoft Corporation, OU=Microsoft IT, CN=Microsoft IT TLS CA 5|CN=*.azurewebsites.net
X-AppService-Proto: https
X-Forwarded-TlsVersion: 1.2

我还需要告诉我的后端应用程序使用转发的 headers 什么(在我的例子中,X-ORIGINAL-HOST 似乎是唯一包含实际请求主机的应用程序)? 这似乎是一个非常直接的用例。 在此先感谢您的帮助。

在主机名设置下的 HTTP 设置中,提及 *.domain.com。如果您进行了更改,请确保您已使用自定义域配置后端。

此致, 马里尼

我只是 运行 喜欢这个。确保在您的选项配置中包含 XForwardedHost,或者像这样只包含 ForwardedHeaders.All

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.All;
});