【问题标题】:ASP.NET Core web api error IDX20803: Unable to obtain configurationASP.NET Core web api 错误 IDX20803:无法获取配置
【发布时间】:2021-08-04 04:22:25
【问题描述】:
  1. 我正在 dot net core web api 中尝试 JSON Web 令牌身份验证 下面是startup.cs中的代码

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = "http://localhost:8091";
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = false,
                        ValidateIssuer = false,
                        ValidateAudience = false

                    };

                });

            services.AddCors(o => o.AddPolicy("AllowOrigins", builder =>
            {
                builder.WithOrigins("http://localhost:5500", "http://127.0.0.1:5500")
                 .AllowAnyMethod()
                 .AllowAnyHeader();
            }));


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            
            app.UseCors("AllowOrigins");
            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

  1. 控制器中的代码如下
    [ApiController]
    [Route("[controller]")]
    [Authorize]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
  1. 使用我在 IIS 的 8091 端口开发和部署的另一个 api 生成 webtoken,并在 jwt.io 中测试以确保它是正确的。

  2. 当我在 Postman 中运行 api 时,我收到以下消息。 我无法理解为什么会收到此错误以及如何修复它。

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
 ---> System.IO.IOException: IDX20807: Unable to retrieve document from: '[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.]'.
   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.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Authorization: Bearer "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIxIiwidW5pcXVlX25hbWUiOiJKb2huIiwibmJmIjoxNjIwOTM4NTAxLCJleHAiOjE2MjEwMjQ5MDEsImlhdCI6MTYyMDkzODUwMX0.-d0sf0ZvD9xnXxvPRTHD2H8Y2okLZvmhfC1kU6tBRPlDA-Wk8_pIv6atKhRFFB6bRpsHa1OGOC781_ZoZnFRww"
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:5861
User-Agent: PostmanRuntime/7.26.2
Postman-Token: ebb7c299-ec14-470a-a367-97ae478656b7

【问题讨论】:

    标签: .net-core jwt


    【解决方案1】:

    您的案例中的异常消息并没有透露太多关于到底发生了什么的细节。这是因为 PII 被隐藏了。

    PII 是个人身份信息。出于隐私原因,身份异常或来自 Microsoft 身份的任何日志记录默认情况下会隐藏该信息。您可以选择在开发过程中显示它。这将帮助您对异常有一些了解。仅在开发过程中启用它可以确保您不会在生产环境中意外抛出有关用户的一些个人信息。

    在您的启动类中,添加显示 PII 的选项。

    Public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            IdentityModelEventSource.ShowPII = true;
        }
    }
    

    这是 PII 属性的文档。 https://docs.microsoft.com/en-us/dotnet/api/microsoft.identitymodel.logging.identitymodeleventsource.showpii?view=azure-dotnet

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 1970-01-01
      • 2021-07-15
      • 2022-11-14
      • 2020-07-30
      • 2021-04-29
      • 2022-01-25
      • 2017-02-03
      • 1970-01-01
      相关资源
      最近更新 更多