在C#中从Azure从keyVault中获取机密 [英] Fetching secrets from keyVault from Azure in c#

查看:421
本文介绍了在C#中从Azure从keyVault中获取机密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,该代码可从KeyVault检索秘密.

I have the following code, which retrieves the Secrets from KeyVault.

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

GetToken方法:

GetToken method :

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.

In GetToken method, I'm fetching the ClientId and ClientSecret from Appconfig.

我认为将这些值保留在Appconfig中并使用它们并不安全.有没有一种方法可以从配置文件中删除并从其他任何地方获取.或者有没有可能解决我的问题的好的方法.

I feel that it is not safe to keep these values in Appconfig and use them. 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.

任何回应都非常感谢!

Any response is highly appreciated!

PS:Mine是用C#开发的Windows服务

PS: Mine is a windows service developed in c#

推荐答案

有没有一种方法可以从配置文件中删除并从其他任何地方获取.或者有没有可能解决我的问题?

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身份验证访问数据库以获取相关信息.

Based on my understanding, you could store the related information into the database. And you could use the windows Authentication to access the database to get the related information.

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

Another way to work with a managed identity is through the Microsoft.Azure.Services.AppAuthentication.

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

通过这种方式,您无需存储相关信息,但是在运行服务之前,需要先使用azure cli登录到azure. AzureServiceTokenProvider类将令牌缓存在内存中.有关更多详细信息,请参阅对自定义服务进行身份验证.

In this way you no need to store the related information, but you need to use azure cli to login to azure first before run the service. The AzureServiceTokenProvider class caches the token in memory. For more detail information please refer to authenticate to custom services.

这篇关于在C#中从Azure从keyVault中获取机密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆