如何使用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)' is obsolete: '这是过时的,将在未来的版本中删除。使用来自Microsoft.Identity.Web的AddMicrosoftWebApiAuthentication代替。见https://aka.ms/ms-identity-web。">

所以我试着把它更新成这样:

services.AddMicrosoftIdentityWebApiAuthentication(_configuration, "AzureAd");

似乎一个"AzureAd"节。Json是传递凭据的唯一方法。如何手动输入Instance、domain、ClientId等?我不用应用程序。在AzureKeyVault中,所有的数据都是手动从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");

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

注意,我还必须删除"api://"从clientId。看起来新版本是自动添加的。它试图验证"api://api://"。

这是一个老问题,但也许值得在这里补充一点。首先,使用Azure KeyVault存储配置值并不能阻止您使用IConfiguration抽象来获取这些值。所有您需要的是Azure.Extensions.AspNetCore.Configuration.Secrets的nuget包,然后注册新的配置源与builder.Configuration.AddAzureKeyVault方法。一般来说,这就是IConfigurationIConfigurationSource抽象的目的。保持应用程序逻辑干净,不去读取配置值,而不管它们的来源是什么。

第二种方法也有更清晰的方法来做到这一点。您可以简单地利用下面使用期权模式的事实。因此,您可以注册自己的IPostConfigureOptions<JwtBearerOptions>实现。例如:

public class AuthenticationOptionsConfiguration : IPostConfigureOptions<JwtBearerOptions>
{
private readonly YourDependency _dependency;

public AuthenticationOptionsConfiguration(YourDependency dependency)
{
_dependency = dependency;
}

public void PostConfigure(string name, JwtBearerOptions options)
{
options.Instance = "https://login.microsoftonline.com/";
options.Domain = _dependency.BackOfficeADDomain;
(...)
}
}

并将其注册到builder.Services.ConfigureOptions<AuthenticationOptionsConfiguration>();,这样您也可以访问options.Events属性并在需要时添加一些处理程序。

最新更新