在 c# 中从 Azure 的 keyVault 获取机密

Fetching secrets from keyVault from Azure in c#

我有以下代码,它从 KeyVault 中检索机密。

var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var sec = await kv.GetSecretAsync(ConfigurationManager.AppSettings["SomeURI"]);
secretValue = sec.Value ;

获取令牌方法:

async Task<string> GetToken(string authority, string resource, string scope)
{
    var authContext = new AuthenticationContext(authority);
    ClientCredential clientCred = new ClientCredential(ConfigurationManager.AppSettings["ClientId"],ConfigurationManager.AppSettings["ClientSecret"]);
    AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);    
    if (result == null)
        throw new InvalidOperationException("Failed to obtain the token");    
    return result.AccessToken;
}

在 GetToken 方法中,我从 Appconfig 获取 ClientIdClientSecret

我觉得将这些值保存在Appconfig中并使用它们是不安全的。有没有一种方法可以从配置文件中删除并从其他任何地方获取。或者有没有什么好的解决方案可以解决我的问题。

非常感谢任何回复!

PS: 我的是用 c#

开发的 windows 服务

Is there a way I can remove from config file and fetch from anywhere else. Or is there any possible good solution to my problem.

根据我的理解,您可以将相关信息存储到数据库中。您可以使用 windows Authentication 访问数据库以获取相关信息。

另一种使用托管身份的方法是通过 Microsoft.Azure.Services.AppAuthentication

var azureServiceTokenProvider = new AzureServiceTokenProvider();
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));

这种方式不需要保存相关信息,但是在运行服务前需要先用azure cli登录azure。 AzureServiceTokenProvider class 将令牌缓存在内存中。更多详细信息请参考authenticate to custom services.