[英]Asp.Net MVC 5 - how to Implement Azure.Security.KeyVault.Secrets code
我正在尝试更新从 ASP.NET MVC 5 创建的应用程序的 .NET 框架
我刚刚发现它使用的是 Microsoft.Azure.KeyVault,它在 nugget 中被声明为已弃用的版本,并建议使用 Azure.Security.KeyVault.Secrets
然而,在代码中实现是这样的:
public static string GetSecretWithCert(string secretNode)
{
string clientId = ConfigurationManager.AppSettings["ClientId"];
string keyVaultName = ConfigurationManager.AppSettings["KeyVaultName"];
string keyVaultCertificateThumbprint = ConfigurationManager.AppSettings["KvThumbprint"];
if (string.IsNullOrWhiteSpace(secretNode)) return string.Empty;
var secretUri = $"https://{keyVaultName}.vault.azure.net/secrets/{secretNode}";
KeyVaultClient keyClient = new KeyVaultClient(async (authority, resource, scope) =>
{
AuthenticationContext authenticationContext = new AuthenticationContext(authority, null);
X509Certificate2 certificate;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
ClientAssertionCertificate clientAssertionCertificate;
try
{
store.Open(OpenFlags.ReadOnly);
var certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, keyVaultCertificateThumbprint, false);
if (certificateCollection.Count == 0)
{
throw new Exception("Certificate not installed in the store");
}
certificate = certificateCollection[0];
clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate);
var result = await authenticationContext.AcquireTokenAsync(resource, clientAssertionCertificate).ConfigureAwait(false);
return result.AccessToken;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
store.Close();
authenticationContext = null;
certificate = null;
clientAssertionCertificate = null;
}
});
SecretBundle secret = null;
try
{
// changed to a sync call with GetAwaiter and GetResult
secret = keyClient.GetSecretAsync(secretUri).GetAwaiter().GetResult();
}
catch (Exception ex)
{
throw (ex);
}
return (secret?.Value);
}
如何使用 Azure.Security.KeyVault.Secrets 库的代码翻译上述代码?
您可以简单地使用下面的示例代码,详细信息请参见此处。
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
var client = new SecretClient(new Uri("https://myvault.azure.vaults.net/"), new DefaultAzureCredential());
KeyVaultSecret secret = await client.GetSecretAsync("secret1");
上面的代码使用DefaultAzureCredential
进行身份验证,如果启用,将尝试以下凭据类型,在您的原始代码中,它使用证书来获取令牌,如果您仍然想保留它,请在上面的代码中使用ClientCertificateCredential
而不是DefaultAzureCredential
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.