c# - Azure AD (MSAL) 身份验证不适用于 ASP.NET 核心 API

标签 c# asp.net-core

我有简单的 asp.net 核心应用程序
启动:

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // This is required to be instantiated before the OpenIdConnectOptions starts getting configured.
            // By default, the claims mapping will map claim names in the old format to accommodate older SAML applications.
            // 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' instead of 'roles'
            // This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
            // JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            // Adds Microsoft Identity platform (AAD v2.0) support to protect this Api
            services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
            services.AddControllers();
    
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "LuloWebApiCoreMac", Version = "v1" });
            });
        }

        // 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.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "LuloWebApiCoreMac v1"));
            }

            app.UseHttpsRedirection();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
程序
public class Program
    {
        public static void Main(string[] args) {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
appsettings.json
{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xx.com.co",
    "TenantId": "xx-c220-48a2-a73f-1177fa2c098e",
    "ClientId": "xx-3737-48a5-a6c0-7e3bc4f9a5c9"
  },
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "https://localhost:44351"
      }
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
如您所见,客户端 ID 已设置
但是,当我执行 dotnet build 和 dotnet run 并转到该站点时,出现此错误:
OptionsValidationException: IDW10106: The 'ClientId' option must be provided.
Microsoft.Extensions.Options.OptionsFactory<TOptions>.Create(string name)
Microsoft.Extensions.Options.OptionsMonitor<TOptions>+<>c__DisplayClass11_0.<Get>b__0()
System.Lazy<T>.ViaFactory(LazyThreadSafetyMode mode)
System.Lazy<T>.ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor)
System.Lazy<T>.CreateValue()
System.Lazy<T>.get_Value()
Microsoft.Extensions.Options.OptionsCache<TOptions>.GetOrAdd(string name, Func<TOptions> createOptions)
Microsoft.Extensions.Options.OptionsMonitor<TOptions>.Get(string name)
Microsoft.Identity.Web.MicrosoftIdentityWebApiAuthenticationBuilderExtensions+<>c__DisplayClass3_0.<AddMicrosoftIdentityWebApiImplementation>b__0(JwtBearerOptions options, IServiceProvider serviceProvider, IOptionsMonitor<MicrosoftIdentityOptions> microsoftIdentityOptionsMonitor)
Microsoft.Extensions.Options.ConfigureNamedOptions<TOptions, TDep1, TDep2>.Configure(string name, TOptions options)
Microsoft.Extensions.Options.OptionsFactory<TOptions>.Create(string name)
Microsoft.Extensions.Options.OptionsMonitor<TOptions>+<>c__DisplayClass11_0.<Get>b__0()
System.Lazy<T>.ViaFactory(LazyThreadSafetyMode mode)
System.Lazy<T>.ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor)
System.Lazy<T>.CreateValue()
System.Lazy<T>.get_Value()
Microsoft.Extensions.Options.OptionsCache<TOptions>.GetOrAdd(string name, Func<TOptions> createOptions)
Microsoft.Extensions.Options.OptionsMonitor<TOptions>.Get(string name)
Microsoft.AspNetCore.Authentication.AuthenticationHandler<TOptions>.InitializeAsync(AuthenticationScheme scheme, HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, string authenticationScheme)
Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, string scheme)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

最佳答案

您应该指定您尝试将配置绑定(bind)到的名称。错误是说它找不到 ClientId .
在您的情况下,这应该是 services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAd");您可以在 ASP.NET Core here 中阅读有关选项模式的更多信息.

关于c# - Azure AD (MSAL) 身份验证不适用于 ASP.NET 核心 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66444919/

相关文章:

c# - Active Directory - 确定域的唯一 ID

c# - EventLog.CreateEventSource 未创建自定义日志

asp.net-core - Microsoft.Extensions.Logging 中是否提供强制日志记录

c# - ASP.NET Core 未同时响应所有请求 Http

c# - 如何在 C# 中将结构转换为字节数组?

c# - 基于泛型解析抽象类

asp.net - 无法使用 asp.net core 身份登录

c# - 处理 Service Fabric 中的聚合异常

c# - 生成的 AAD CallbackUrl 是 IP 地址,与部署到服务结构时应用程序注册中的回复 Url 不匹配

c# - Silverlight 中 PictureBox 的替代品是什么?