CrazyCoder
CrazyCoder

Reputation: 2388

Fetching secrets from keyVault from Azure in c#

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 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;
}

In GetToken method, I'm fetching the ClientId and ClientSecret from 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 is a windows service developed in c#

Upvotes: 1

Views: 1513

Answers (1)

Tom Sun
Tom Sun

Reputation: 24569

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.

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.

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));

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.

Upvotes: 1

Related Questions