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

.Net Core微服务Docker化后调用IdentityServer4报错求助

问题原因

容器内的localhost和宿主机的localhost属于不同网络命名空间,MVC客户端容器用https://localhost:5005/无法访问到宿主机或其他容器内的IdentityServer服务,导致无法获取OpenID配置文档。

解决方案

1. 同Docker Compose网络内使用服务名访问(推荐)

如果IdentityServer也是通过Docker Compose部署的服务:

  • 修改MVC客户端的Authority配置为IdentityServer在docker-compose.yml中定义的服务名称,比如假设IdentityServer的服务名为identityserver,则:
options.Authority = "https://identityserver:5005/";
  • 确保MVC客户端和IdentityServer服务在同一个Docker网络中(默认Docker Compose会为同文件内的服务创建并加入默认网络,无需额外配置)。
  • 处理HTTPS证书问题:
    • 开发环境可临时禁用证书验证(仅用于测试):
      options.BackchannelHttpHandler = new HttpClientHandler
      {
          ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
      };
      
    • 生产环境需将IdentityServer的证书导入到MVC客户端容器的信任根证书库。

2. 映射端口后使用宿主机IP访问

如果IdentityServer运行在宿主机,或已将容器端口映射到宿主机:

  • 将Authority配置改为宿主机的局域网IP地址(不要用localhost),比如:
options.Authority = "https://192.168.1.100:5005/";
  • 确保宿主机防火墙开放5005端口,允许容器网络访问。
修改后的Startup代码示例
services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    // 替换为服务名或宿主机IP
    options.Authority = "https://identityserver:5005/";
    options.ClientId = "taxationclient_presentation";
    options.ClientSecret = "secret";
    options.ResponseType = "code";
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.SaveTokens = true;
    options.GetClaimsFromUserInfoEndpoint = true;

    // 开发环境临时禁用证书验证
    options.BackchannelHttpHandler = new HttpClientHandler
    {
        ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
    };
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:45:33