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

.NET Core 5反向代理/负载均衡下OpenId重定向URI配置问询

解决方案完整配置示例

1. 配置反向代理头部转发

在ConfigureServices中先配置ForwardedHeaders,让应用信任反向代理传递的外部请求信息:

public void ConfigureServices(IServiceCollection services)
{
    // 配置反向代理头部转发,信任代理IP(生产环境请指定具体代理IP)
    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
        // 替换为你的反向代理实际IP地址
        options.KnownProxies.Add(IPAddress.Parse("10.20.0.xxx"));
        options.ForwardLimit = null;
    });

    var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');

    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
            .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                .AddInMemoryTokenCaches();

    // 动态配置OpenIdConnect重定向URI,从配置文件读取避免硬编码
    services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        var productionRedirectUri = Configuration.GetValue<string>("AzureAd:ProductionRedirectUri");
        if (!string.IsNullOrEmpty(productionRedirectUri))
        {
            options.Events.OnRedirectToIdentityProvider = context =>
            {
                context.ProtocolMessage.RedirectUri = productionRedirectUri;
                return Task.CompletedTask;
            };
        }

        // 配置登出回调地址(可选)
        options.Events.OnRedirectToIdentityProviderForSignOut = context =>
        {
            context.ProtocolMessage.PostLogoutRedirectUri = Configuration.GetValue<string>("AzureAd:PostLogoutRedirectUri");
            return Task.CompletedTask;
        };
    });

    services.AddControllersWithViews();
}

2. 在Configure方法中启用头部转发中间件

注意将UseForwardedHeaders放在认证中间件之前:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    // 启用反向代理头部转发,必须放在UseAuthentication之前
    app.UseForwardedHeaders();

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

    app.UseRouting();

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

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

3. 配置文件(appsettings.json)补充

添加生产环境重定向URI,实现多环境灵活切换:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "your-domain.com",
    "TenantId": "your-tenant-id",
    "ClientId": "your-client-id",
    "ClientSecret": "your-client-secret",
    "CallbackPath": "/signin-oidc",
    "ProductionRedirectUri": "https://example.com/signin-oidc",
    "PostLogoutRedirectUri": "https://example.com/signout-callback-oidc"
  },
  "DownstreamApi": {
    "Scopes": "User.Read Mail.Read",
    "BaseUrl": "https://graph.microsoft.com/v1.0"
  }
}

关键说明

  • ForwardedHeaders是核心配置:让应用从反向代理传递的X-Forwarded-Proto和X-Forwarded-Host头部获取真实的外部协议与域名,而非内部IIS绑定地址。
  • 避免硬编码URI:通过配置文件读取,方便本地/生产环境切换,同时确保Azure AD门户已添加对应URI。
  • 生产环境务必指定具体代理IP:不要使用AllowAny,降低安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:02:32