<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

How to Store and Retrieve Secrets in Azure

Swapnil Thitame Mar 06, 2023

security Azure Cloud Secrets Azure Key Vault API Keys

Azure Key Vault is a cloud service that provides a secure place to store secrets. It enables the safe storage of API (Application Program Interface) keys, passwords, certificates, database connection strings, and other secrets. The Azure portal is used to build and manage Azure Key Vaults.

Following are the steps to store the secrets in Azure Key Vaults:

  1. Click on the link to login into the Azure portal: https://portal.azure.com/

    Create Resource in Azure
  2. Click on create a resource or search key vault in the search box.
  3. Select Key Vault from the results.
  4. Select ‘Create'.

    Create key vault in azure
  5. Provide a Name for the resource group (i.e., Dev/QA/Prod) and key vaults name (i.e., dev-kv) Click on the review and create button.
  6. Once created key vaults (i.e., dev-kv) go to these key vaults and open settings.
  7. In the settings section, click on secret then Generate/Import secret.

    import Secret in azure
  8. In the last step, a window will be displayed to generate a secret. Add the Secret name (ConnectionString) and its value (UserID=postgres;Password=123;Host=localhost;Port=5432;Database=PostgreSqlDemoDb).

    Create secret in azure

By using above steps, we can create key vaults for Dev, QA, and Production environment so they can be easily maintained.

How to retrieve secret (ConnectionString, Password etc.) from Azure key vaults in C#.

There are two ways for retrieving a secret from Azure key vaults in C#.

  • Using Client Credentials: -

    By using client credentials (App_Client_id, App_Client_secret, KeyVaultUri) can retrieve secrete from azure key vaults.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Mvc;
    using Microsoft.AspNetCore.DataProtection;
    using Microsoft.Azure.KeyVault;
    using Microsoft.IdentityModel.Clients.ActiveDirectory; 

     namespace RetrieveKeyUsingCredential

    {

        internal class SecurityController: Controller

        {

            private readonly IDataProtector _dataProtector;

            public SecurityController(IDataProtectionProvider dataprovider)

            {

                this._dataProtector = dataprovider.CreateProtector("POC");

            }

            public void Main()

            {

                // Add below actual client credentials.

                String App_Client_id = "";

                String App_Client_secret = "";

                String KeyVaultUri = "";

                String ClientidEncrypt = this._dataProtector.Protect(App_Client_id);

                String ClientsecretEncrypt = this._dataProtector.Protect(App_Client_secret);

                string Clientiddecrypt = this._dataProtector.Unprotect(ClientidEncrypt);

                String Clientsecretdecrypt = this._dataProtector.Unprotect(ClientsecretEncrypt);

                //Above code used for encrypt and decrypt the client id.

                var kvc = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async (string authority, string

                               resource, string scope) =>

                 {

                    var authContext = new AuthenticationContext(authority);

                    var credential = new ClientCredential(Clientiddecrypt, Clientsecretdecrypt);

                    AuthenticationResult result = await authContext.AcquireTokenAsync(resource, credential);

                    if (result == null)

                    {

                        throw new InvalidOperationException("Failed to retrieve secret from Azure key vaults");

                    }

                    return result.AccessToken;

                }

                ));

                var secretBundle = kvc.GetSecretAsync(KeyVaultUri, "ConnectionString").Result;

                //ConnectionString:Name of secret is case sensitive. The name should be same which is added in key vaults. 

                Console.WriteLine("Connection String Secret Value:" + secretBundle.Value);

                Console.ReadKey();

            }

        }

    }

  • Without Client Credentials:-
Without client credentials, we can retrieve a secret from Azure Key Vault but the developer/user should have access to key vaults. Following are steps for adding read-only access for Key Vaults.
  • Go to key vaults (dev-kv)
  • Click on Access policies
  • Add user and give access to retrieve the secret
Source code:

using System;

using Azure.Security.KeyVault.Secrets;

using Azure.Identity;

string KeyVaultURL = ""; 

var secretclient = new SecretClient(new Uri(KeyVaultURL), new DefaultAzureCredential());

var connectionString = await secretclient.GetSecretAsync("ConnectionString");

 //ConnectionString:Name of secret is case sensitive. The name should be same which is added in key vaults.

String SecretValue = connectionString.Value.Value;

Console.WriteLine("Connection String secret value:" + SecretValue);

Console.ReadKey();

We can conclude, referencing Azure Key Vault secrets is a safe and secure way to use credentials.

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.