asp.net core 2.2 web api“未指定 authenticationScheme,并且没有找到 DefaultChallengeScheme”错误 Azure AD

问题描述

配置看起来没问题。但我在尝试添加基于 Azure AD 的身份验证时遇到错误

Startup.cs => ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddAzureADBearer(options => Configuration.Bind("AzureAd",options));

    // Rest of the code
}

Startup.cs => Configure

public void Configure(IApplicationBuilder app,IMicrosoftServersHealthCheckService microsoftServersHealthCheckService)
{
    _logger.LogTrace($"Inside Configure for Environment: {Environment.EnvironmentName}");
            
    app.UseMiddleware<APIResponseMiddleware>();
    app.UseExceptionHandler(errorApp =>
    {
        errorApp.Run(async context =>
        {
            var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
            var exception = errorFeature.Error;
            _logger.LogError(exception,exception.Message);
            ExceptionHandlerFilter.HandleExceptionAsync(context,exception).Wait();
        });
    });
    
    if (Environment.IsDevelopment())
    {
        // The following will be picked up by Application Insights.
        _logger.Loginformation("Configuring for Development environment");
        //app.UseDeveloperExceptionPage();                
    }
    else
    {
        // The following will be picked up by Application Insights.
        _logger.Loginformation($"Configuring for {Environment.EnvironmentName} environment");
        // The default HSTS value is 30 days. You may want to change this for production scenarios,see https://aka.ms/aspnetcore-hsts.
        //app.UseHsts();
    }

    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json","DNS API");

    });

    app.UseAuthentication();
    app.UseMvc();
    
}

Message: "No authenticationScheme was specified,and there was no DefaultChallengeScheme found."

Stack Trace: system.invalidOperationException: No authenticationScheme was specified,and there was no DefaultChallengeScheme found.\r\n at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context,String scheme,AuthenticationProperties properties)\r\n at Microsoft.AspNetCore.Mvc.ChallengeResult.ExecuteResultAsync(ActionContext context)\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterasync[TFilter,TFilterasync]()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterasync](State& next,Scope& scope,Object& state,Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAlwaysRunResultFilters()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()\r\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)\r\n at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)\r\n at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)\r\n at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext,ISwaggerProvider swaggerProvider)\r\n at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)

解决方法

如果你想使用Azure AD来项目你的web API,请参考下面的代码

  1. 安装包
Install-Package Microsoft.Identity.Web -Version 1.6.0
  1. 代码
public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration,"AzureAd");
    }

public void Configure(IApplicationBuilder app,IHostingEnvironment env)
{
    // more code
    app.UseAuthentication();
    app.UseAuthorization();
    // more code
}

详情请参考herehere