Azure Key Vault & Access from C#
In this article we can explore how to create an Azure Key Vault & Access from C#.
Azure Key Vault
Azure Key Vault allows to keep encrypted secured strings. Eg: Connection Strings, Passwords etc.
Create Azure Key Vault
Open Azure Portal & Create a new Key Vault as shown below.
Go the Secrets blade and create a new Secret with name as key1 and value as value1
Create App Registration
We need to create an App Registration for our Console Application. This will enable to Authenticate our Console Application using the Credentials.
Go to Azure Portal > Azure Active Directory > App Registrations. Create new App Registration as below.
Create new client secret too.
Now copy the Client ID and Client Secret which you need in the next steps.
Authorize Console Application
We need to Authorize the Console Application to the Key Vault. Without this step you will get Forbidden error.
Go to Key Vault > Access Policies blade
Click Add Access Policy and select our Console Application as Principal.
Now onwards any application authenticated through Client Credentials of the Console App Registration will be considered as Principal – which is the Security Identity for the application.
Create Project
Create a new console application in Visual Studio. Add references to following:
· Microsoft.Azure.KeyVault
· Microsoft.IdentityModel.Clients.ActiveDirectory
Replace the code with following.
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading.Tasks;
namespace KeyVault
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($”Secret Value from Vault is: {GetVaultValue()}”);
Console.ReadKey(false);
}
static string GetVaultValue()
{
KeyVaultClient client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
var vaultAddress = “https://your-key-vault.vault.azure.net”;
var secretName = “key1”;
var secret = client.GetSecretAsync(vaultAddress, secretName).GetAwaiter().GetResult();
return secret.Value;
}
static async Task GetToken(string authority, string resource, string scope)
{
var clientId = “YOUR CLIENT ID”;
var clientSecret = “YOUR CLIENT SECRET”;
ClientCredential credential = new ClientCredential(clientId, clientSecret);
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, credential);
return result.AccessToken;
}
}
}
On running the application, you will get the following output.
References
Summary
In this article we have explored how to create an Azure Key Vault & Access from C#.
Really nice article, can you also write about hot to set secret key
LikeLike
Hi Virendra, here it is: https://jeanpaul.cloud/2020/03/07/create-key-vault-secret/
LikeLike