如何在 C# 中修复“IDX20804: 无法从:'[PII is hidden]'”的错误

36

我正在尝试获取访问令牌以在我的WebApi中使用MS Graph。但是一直收到此错误消息:

[TaskCanceledException: 已取消任务。] System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +167 . .

[IOException: IDX20804: 无法从 '[PII已隐藏]' 检索文档。] Microsoft.IdentityModel.Protocols.d__8.MoveNext() +662 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99 . . [InvalidOperationException: IDX20803: 无法从 '[PII已隐藏]' 获取配置。] Microsoft.IdentityModel.Protocols.d__24.MoveNext() +1586 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99

我尝试了在网上找到的所有解决方法。

我正在使用这个repo作为身份验证部分的参考。

我该如何修复?


1
搜索结果显示了许多不同的原因导致了这个错误。我在第二次测试IdentityServer4样例时遇到了这个错误。之前所有的原始样例都可以正常工作。而且第一个样例(客户端凭证)今天也可以正常工作。但是在安装Telerik Fiddler之后,所有这些都被破坏了。Fiddler要求点击一个按钮来配置一些系统默认设置。它做了一些我无法回忆起的事情,但我立即停止使用fiddler。然后在我得到这个错误后,我重新启动了计算机,现在一切都正常工作。 - Dush
9个回答

23

首先,要解决这个问题,您需要找出错误在哪里。将以下代码放入您的 Startup.cs 中以显示真正的错误(不建议在生产环境中使用):

app.UseDeveloperExceptionPage();
if (env.IsDevelopment())
{
    IdentityModelEventSource.ShowPII = true;
}

就我个人而言,在公司内部网络中本地运行时,我遇到了代理问题。


2
这应该被标记为解决问题的方案。谢谢Robert! - g0rski
我遇到了一个与本地代理相关的问题,你是如何解决的? - Ashlanfox
我记得我当时使用的是MailKit来发送电子邮件,而且我还需要在本地开发环境中设置电子邮件客户端的代理。smtpClient.ProxyClient = new HttpProxyClient("proxy.mycompany.com", 80); - Robert Brooker
@RobertBrooker 如果我必须在测试环境中尝试这个(而不是在本地调试模式下)。日志会在哪里呢?我正在使用NLog,我已将IdentityModelEventSource.ShowPII设置为true(在env.IsDevelopment()if条件之外)。然而,日志显示IDX20804: 无法从:'[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'检索文档。 - undefined
@Sampath 如果运行了 ShowPII = true,那么异常信息中应该包含这个内容。我不确定在你的情况下出了什么问题。 - undefined
显示剩余2条评论

10

我遇到了以下问题

[IOException: IDX20804:无法从“[PII is hidden]”检索文档。] Microsoft.IdentityModel.Protocols.d__8.MoveNext() +662 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99 ... [InvalidOperationException:IDX20803:无法从“[PII is hidden]”获取配置。] Microsoft.IdentityModel.Protocols.d__24.MoveNext() +1586 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99

以下解决方案解决了我的问题。 我在startup.cs中添加了以下代码

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

注意:要获取有关异常的详细信息,请添加以下行。 您将能够更详细地了解此问题。

Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;


"...Tls12"修复了我遇到的底层连接已关闭: 发生了意外错误的内部异常。谢谢! - undefined

7
当我创建一个新的 Blazor 应用程序时,遇到了类似的错误 -> Blazor 服务器应用程序,具有单独的用户帐户 -> 连接到云中的现有用户存储 (Azure AD B2C)。

enter image description here

IOException: IDX20807: 无法从 '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' 检索文档。HttpResponseMessage: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]',HttpResponseMessage.Content: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'。Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string address, CancellationToken cancel)
InvalidOperationException: IDX20803: 无法从 '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' 获取配置。Microsoft.IdentityModel.Protocols.ConfigurationManager.GetConfigurationAsync(CancellationToken cancel)
请确保在appsettings.json中将域设置为您的Azure AD B2C域,而不是完整的App ID URI。例如,使用<tenant-name>.onmicrosoft.com而不是<tenant-name>.onmicrosoft.com/api。还要查看appsettings.json中的AzureAdB2C ->实例。我将其默认值设置为https://login.microsoftonline.com/tfp,但它无效,当我将其更改为https://<tenant-name>.b2clogin.com/tfp/时,一切都开始正常工作。

1
如果您投票反对,请说明原因。否则很难改进答案。 - Ogglas
2
这个解决方案用 Blazor Server 解决了我的问题。 - Juan Mitchell

4

我也一样,在没有任何成功的情况下阅读了以下内容。我的设置是工作的,但是当我尝试在另一台机器上加载它时,我遇到了这个问题。

以下是堆栈跟踪,我得到了两个不同应用程序的http状态码400和404。

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden]'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden]'. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)   at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
   at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleChallengeAsync(AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.ChallengeAsync(AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
   at Microsoft.AspNetCore.Mvc.ChallengeResult.ExecuteResultAsync(ActionContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAlwaysRunResultFilters()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
   HIDDEN LINE
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.FeaturePolicy.FeaturePolicyMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.ReferrerPolicy.ReferrerPolicyMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.XContentTypeOptions.XContentTypeOptionsMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.XXssProtection.XXssProtectionMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.XFrameOptions.XFrameOptionsMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.Csp.CspMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden]'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: '[PII is hidden]'. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)   at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
   at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
   --- End of inner exception stack trace ---
   at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
   at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleChallengeAsync(AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.ChallengeAsync(AuthenticationProperties properties)
   at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
   at Microsoft.AspNetCore.Mvc.ChallengeResult.ExecuteResultAsync(ActionContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAlwaysRunResultFilters()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
   HIDDEN LINE
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.FeaturePolicy.FeaturePolicyMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.ReferrerPolicy.ReferrerPolicyMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.XContentTypeOptions.XContentTypeOptionsMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.XXssProtection.XXssProtectionMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.XFrameOptions.XFrameOptionsMiddleware.Invoke(HttpContext context)
   at Joonasw.AspNetCore.SecurityHeaders.Csp.CspMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

其他讨论此错误的文章。

https://github.com/IdentityServer/IdentityServer4/issues/2337

https://github.com/IdentityServer/IdentityServer4/issues/2672

https://github.com/okta/samples-aspnetcore/issues/10

https://github.com/IdentityServer/IdentityServer4/issues/2186

解决方案: 事实证明,我没有在appsettings.json中配置AzureAD。 我忘记了使用我的User Secrets来配置AzureAD并提供有效凭据。

enter image description here

您需要将以下凭据设置为自己的AzureAd凭据。

{
  "AzureAd": {
    "TenantId": "SOMETHING.onmicrosoft.com",
    "ClientId": "SOMETHING",
    "ClientSecret": "SOMETHING"

  }
}

3
当设置以下标志时,您可以获得更详细的错误消息:IdentityModelEventSource.ShowPII = true; - Carlo Bos
3
你会把你的“旗帜”放在哪里? - Captain Kenpachi
在ASP.NET应用程序中,您可以将此代码放置在Global.asax.cs的Application_Start()方法中。在.Net Core中,您可以将其添加到Startup.cs的ConfigureServices()方法中。 - Carlo Bos

2
我遇到了同样的问题,这是因为它必须通过DockerNAT。 (可能并非每个人都获得此IP地址)
以下是我解决问题的方法:
  1. 打开命令提示符
  2. 键入ipconfig
您将会得到类似于以下内容:
Windows IP Configuration
Ethernet adapter vEthernet (DockerNAT):
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 10.0.75.1 Subnet Mask . . . . . . . . . . . : 255.255.255.240
Default Gateway . . . . . . . . . :

  1. Basically copy that IP address to your docker-compose.yml file

    services:

    webmvc:

    build:
    
      context: .\src\Web\WebMvc
    
      dockerfile: Dockerfile
    
    environment:
    
      - IdentityUrl=http://10.0.75.1:5000/ #Change IP and Port
    
    container_name: test
    
    ports:
    
      - "5200:80"
    
    networks:
    
      - frontend
    
    depends_on:
    
      - tokenserver #your identityserver4 service
    
  2. Other things to check are:

请确保在您的Startup.cs文件的ConfigureServices方法(WebMvc项目)中包含以下内容,并且它们在您的yml文件中拼写正确。原始答案翻译成"最初的回答"。
        var identityUrl = Configuration.GetValue<string>("IdentityUrl");
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOpenIdConnect(options => {
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;             
            options.Authority = identityUrl.ToString();
            options.SignedOutRedirectUri = "http://localhost:5200/"; //Change to your mvc address
            options.ClientId ="mvc";
            options.ClientSecret = "secret";
            options.ResponseType =  "code id_token";
            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = true;
            options.RequireHttpsMetadata = false;
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("offline_access");
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                NameClaimType = "name",
                RoleClaimType = "role"
            };
        });

除此之外,您可能需要在防火墙上打开端口。在我的情况下,我必须打开5000端口。
a. 打开控制面板
b. 系统和安全
c. Windows Defender 防火墙
d. 高级设置
e. 入站规则 => 新建规则...
f. 规则类型 => 端口 ==> 点击下一步
g. 选择协议下的TCP
h. 特定本地端口 => 输入5000
i. 点击下一步 => 选择允许连接
j. 点击下一步
k. 我在何时应用规则下勾选了所有选项 l. 点击下一步 => 输入Docker端口 => 点击完成

真糟糕,浪费了几天时间在开发者证书等问题上,最终发现将 IP 地址更改为 Docker NAT 的地址就可以解决问题。谢谢你,你救了我! - Remus.A

1
我将以下代码添加到startup.cs中,问题得到了解决:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

没错,这就是我的问题所在...非常感谢。 - undefined

0

0

-1

我的问题通过在startup.cs文件的configuration方法中添加以下代码得到解决。 IdentityModelEventSource.ShowPII = true;


2
这只是启用了额外的个人身份信息日志记录,以便 OP 日志中的 [PII is hidden] 部分得到填充;它不能解决问题。 - Zimano
这对我有用...我尝试的其他所有方法都失败了。 - Soundar Rajan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接