我有这个非常简单的 .NET Core 应用程序:
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
builder.AddAzureKeyVault("https://MyKeyVault.vault.azure.net");
var stopwatch = new Stopwatch();
stopwatch.Start();
var configuration = builder.Build();
var elapsed = stopwatch.Elapsed;
Console.WriteLine($"Elapsed time: {elapsed.TotalSeconds}");
}
csproj 文件如下所示:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.1" />
</ItemGroup>
</Project>
我的问题是,在附加调试器的情况下应用程序需要大约 10 秒才能执行(没有调试器大约需要 5 秒)。如果我使用 AddAzureKeyVault 删除该行,应用程序将在不到一秒的时间内执行。我知道 AddAzureKeyVault 将使应用程序连接到 Azure 并从 key 保管库读取值,但我预计这会快得多。
这是预期的行为吗?我可以做些什么来加快速度吗?
最佳答案
对于Microsoft.Azure.Services.AppAuthentication图书馆,请参阅原始答案。对于较新的Azure.Identity库,请参阅更新 2021-03-22。
<小时/>原始答案:
是的,显式配置 AzureServiceTokenProvider
以使用 az cli
进行身份验证。您可以通过设置名为 AzureServicesAuthConnectionString
的环境变量来执行此操作。
重击:
export AzureServicesAuthConnectionString="RunAs=Developer; DeveloperTool=AzureCli"
PowerShell:
$Env:AzureServicesAuthConnectionString = "RunAs=Developer; DeveloperTool=AzureCli"
请注意,需要在运行应用程序的任何 session 中设置环境变量。
说明
问题的根源在 MS docs on authentication 中有所暗示。 ,其中指出“默认情况下,AzureServiceTokenProvider
使用多种方法来检索 token 。”
在使用的多种方法中,az cli
身份验证排名靠后。因此,AzureServiceTokenProvider
需要一些时间来尝试其他优先顺序较高的身份验证方法,然后才能最终使用 az cli
作为 token 源。在环境变量中设置连接字符串可以消除您等待其他身份验证方法失败所花费的时间。
此解决方案优于对 clientId
和 clientSecret
进行硬编码,不仅是为了方便,而且还因为 az cli
auth 不需要硬编码您的 clientSecret
或以明文形式存储。
更新(2021-03-22)
Azure.Identity 身份验证提供程序与较新的 Azure 客户端 SDK(例如 Azure.Security.KeyVault.Secrets
)兼容,具有基于代码的选项(而不是连接字符串)来跳过某些身份验证方法。您可以:
在 DefaultAzureCredential constructor 中设置排除项,或
使用 more specific class type constructors 生成 TokenCredential (另请参阅身份验证提供程序迁移图表 here )。
关于azure - 使用 AddAzureKeyVault 使我的应用程序慢了 10 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53068620/