客户端和 .Net Core 之间的 AAD 身份验证 API

AAD Authentication between client and .Net Core API

当我从客户端到达 API 时收到此错误。我使用 MSAL,我可以在请求中看到令牌已加载。

这是我的启动配置。

public void ConfigureServices(IServiceCollection 服务) { services.AddControllers();

        services.AddAuthentication(defaultScheme: AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options =>
        {
            options.ClientId = "example";
            options.TenantId = "example";
            options.ClientSecret = "example";
            options.Instance = "https://login.microsoftonline.com/";
        });

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("https://localhost:5001", "http://localhost:5000")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                        .WithExposedHeaders("Content-Disposition");
                });
        });
    }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors();

        //app.UseCors(options =>
        //{
        //    options.WithOrigins("https://localhost:5001", "http://localhost:5000")
        //        .AllowAnyHeader()
        //        .AllowAnyMethod()
        //        .AllowCredentials()
        //        .WithExposedHeaders("Content-Disposition");
        //});

        app.UseRouting();


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

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

我解决了链入配置服务这样的问题:

 services.AddAuthentication(defaultScheme: AzureADDefaults.JwtBearerAuthenticationScheme)
                .AddAzureADBearer(options =>
                {
                    options.Instance = Environment.GetEnvironmentVariable("AAD_INSTANCE");
                    options.TenantId = Environment.GetEnvironmentVariable("AAD_TENANT_ID");
                    options.ClientId = Environment.GetEnvironmentVariable("AAD_CLIENT_ID");
                    options.ClientSecret = Environment.GetEnvironmentVariable("AAD_CLIENT_SECRET");
                });