使用ManagedIdentity访问AzureKeyVaults会引发偶发异常

时间:2020-08-05 10:14:26

标签: c# .net azure azure-keyvault azure-managed-identity

我试图从部署在AppService上的.NET Framework应用程序访问AzureKeyVault。通常可以正常工作,但是当我转储AppService日志时,每隔几个小时就会发生以下异常:

<Data>TargetInvocationException</Data><Data>Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Owin.Loader.DefaultLoader.&lt;&gt;c__DisplayClass19_1.&lt;MakeDelegate&gt;b__0(IAppBuilder builder)
   at Owin.Loader.DefaultLoader.&lt;&gt;c__DisplayClass9_0.&lt;LoadImplementation&gt;b__0(IAppBuilder builder)
   at Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup)
   at Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup)
   at Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint()
   at System.Threading.LazyInitializer.EnsureInitializedCore[T](T&amp; target, Boolean&amp; initialized, Object&amp; syncLock, Func`1 valueFactory)
   at Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context)
   at System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers)
   at System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context)
   at System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context)
   at System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext)

Parameters: Connection String: RunAs=App;, Resource: https://vault.azure.net, Authority: https://login.windows.net/###obfuscated_guid###. Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. An error occurred while sending the request.

这是我的代码导致此情况:

 var azureServiceTokenProvider = new AzureServiceTokenProvider("RunAs=App;");
 var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

 keyVaults.ForEach(keyVault => configurationBuilder.AddAzureKeyVault(
     $"https://{keyVault}.vault.azure.net/",
     keyVaultClient,
     new DefaultKeyVaultSecretManager()));

我正在尝试以这种方式加载两个关键文件库。两者都配置了允许我的AppService调用它们的访问策略(对Secrets的“获取”和“列出”权限)。我还为我的AppService启用了“系统分配的身份”。

您是否有任何关于如何解决此问题的建议?预先感谢!

1 个答案:

答案 0 :(得分:0)

感谢大家的评论,

答案比我预期的要简单得多。我向AppService添加了preprod插槽,并假定该配置以及托管身份配置会自动复制。不幸的是,不是。

将托管身份添加到preprod插槽并将preprod插槽添加到KeyVault中的“策略”即可解决此问题。

相关问题