如何在没有应用程序设置部分的情况下使用 AddMicrosoftIdentityWebApiAuthentication?

J F*_*lex 10 azure azure-active-directory microsoft-identity-platform microsoft-identity-web

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

这是旧的工作代码:

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;
    });
Run Code Online (Sandbox Code Playgroud)

但自从更新到 .NET 5 后,我收到以下警告:

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

所以我尝试将其更新为:

services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAd");
Run Code Online (Sandbox Code Playgroud)

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

谢谢你!

小智 10

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

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

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

services.AddMicrosoftIdentityWebApiAuthentication(azureAdConfig);
Run Code Online (Sandbox Code Playgroud)


J F*_*lex 6

好的,我找到了!

这实际上非常简单:

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");
Run Code Online (Sandbox Code Playgroud)

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

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