【问题标题】:How use AddMicrosoftIdentityWebApiAuthentication without appsettings section?如何在没有 appsettings 部分的情况下使用 AddMicrosoftIdentityWebApiAuthentication?
【发布时间】:2021-03-04 15:02:47
【问题描述】:

我正在 .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)' is obsolete: '这是过时的,将在未来的版本中删除。改用 Microsoft.Identity.Web 中的 AddMicrosoftWebApiAuthentication。请参阅 https://aka.ms/ms-identity-web。'

所以我尝试将其更新为:

services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAd");

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

谢谢!

【问题讨论】:

    标签: azure azure-active-directory microsoft-identity-platform microsoft-identity-web


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      好的,我找到了!

      其实很简单:

      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://”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-11
        • 2016-11-29
        • 1970-01-01
        • 2015-02-26
        • 1970-01-01
        • 2018-07-29
        • 2021-10-30
        • 2015-11-12
        相关资源
        最近更新 更多