如何在没有 appsettings 部分的情况下使用 AddMicrosoftIdentityWebApiAuthentication?

问题描述

我正在 .NET 5 API 中实现 Azure Active Directory。 我目前在 .NET Core 2.2 上完美运行了这个 API。

这是旧的工作代码

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
    .AddAzureADBearer(options =>
    {
         options.Instance = "https://login.microsoftonline.com/";
         options.Domain = backOfficeADDomain;
         options.TenantId = backOfficeADTenantId;
         options.ClientId = $"api://{backOfficeADapiclientId}";
         options.ClientSecret = backOfficeADAPISecret;
    });

但是自从更新到 .NET 5 后,我收到了这个警告:

'AzureADAuthenticationBuilderExtensions.AddAzureADBearer(AuthenticationBuilder,Action)' 已过时:'这已过时,将在未来版本中删除。请改用 Microsoft.Identity.Web 中的 AddMicrosoftWebApiAuthentication。请参阅 https://aka.ms/ms-identity-web。'

所以我尝试将其更新为:

services.AddMicrosoftIdentityWebApiAuthentication(_configuration,"AzureAd");

似乎 appsettings.json 中的“AzureAd”部分是传递凭据的唯一方法。如何手动输入实例、域、ClientId 等?我不使用 appsettings.json,所有数据都是从 Azurekeyvault 手动检索的。

谢谢!

解决方法

假设您有充分的理由不使用设置中的配置值,您可以添加内存提供程序。

您还可以创建仅用于此扩展方法的配置:

var azureAdConfig = new ConfigurationBuilder()
    .AddInMemoryCollection(new Dictionary<string,string>
    {
        {"AzureAd:Instance","https://login.microsoftonline.com/"},{"AzureAd:Domain",backOfficeADDomain}
        //...
    })
    .Build();

services.AddMicrosoftIdentityWebApiAuthentication(azureAdConfig);
,

好的,我找到了!

其实很简单:

IConfigurationSection azureAdSection = _configuration.GetSection("AzureAd");

azureAdSection.GetSection("Instance").Value = "https://login.microsoftonline.com/";
azureAdSection.GetSection("Domain").Value = backOfficeADDomain;
azureAdSection.GetSection("TenantId").Value = backOfficeADTenantId;
azureAdSection.GetSection("ClientId").Value = backOfficeADAPIClientId;
azureAdSection.GetSection("ClientSecret").Value = backOfficeADAPISecret;

services.AddMicrosoftIdentityWebApiAuthentication(_configuration,"AzureAd");

经过一整天复杂的代码重构,我的大脑似乎无法理解这么简单的解决方案。

请注意,我还必须从 clientId 中删除“api://”。看起来新版本会自动添加它。它试图验证“api://api://”。