Skip to content

a-patel/azure-key-vault-labs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

18 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Azure Key Vault (with .NET) Labs

Demo: Azure Key Vault + .NET 5.x

Please refer to below article(s) of my publication Awesome Azure on Azure Key Vault:


Usage: Web/API Application ๐Ÿ“„

Step 1 : Install the package ๐Ÿ“ฆ

To install NuGet, run the following command in the Package Manager Console

PM> Install-Package Azure.Security.KeyVault.Secrets
PM> Install-Package Microsoft.Extensions.Configuration.AzureKeyVault
PM> Install-Package Azure.Identity

Step 2 : Configuration ๐Ÿ”จ

Here are samples that show you how to config.

2.1 : AppSettings
{
  // Way-1: Connect to Azure App Configuration using the Managed Identity (for Production Scenario)
  "AzureKeyVaultEndpoint": "https://<YourKeyVaultName>.vault.azure.net",

  // Way-2: Connect to Azure App Configuration using the Connection String (for Development Scenario)
  "AzureKeyVault": {
    "Endpoint": "https://<YourKeyVaultName>.vault.azure.net",
    "ClientId": "<YourKeyVaultClientId>",
    "ClientSecret": "<YourKeyVaultClientSecret>"
  },

  "Settings": {
    "AppName": "Azure Key Vault Labs",
    "Version": 1.0,
    "FontSize": 50,
    "RefreshRate": 1000,
    "Language": "English",
    "Messages": "Hello There. Thanks for using Azure Key Vault.",
    "BackgroundColor": "Black"
  }
}
2.2 : Configure Program Class
public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                var settings = config.Build();

                if (!context.HostingEnvironment.IsDevelopment())
                {
                    // Way-1
                    // Connect to Azure Key Vault using the Managed Identity.
                    var keyVaultEndpoint = settings["AzureKeyVaultEndpoint"];

                    if (!string.IsNullOrEmpty(keyVaultEndpoint))
                    {
                        var azureServiceTokenProvider = new AzureServiceTokenProvider();
                        var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                        config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
                    }
                }
                else
                {
                    // Way-2
                    // Connect to Azure Key Vault using the Client Id and Client Secret (AAD) - Get them from Azure AD Application.
                    var keyVaultEndpoint = settings["AzureKeyVault:Endpoint"];
                    var keyVaultClientId = settings["AzureKeyVault:ClientId"];
                    var keyVaultClientSecret = settings["AzureKeyVault:ClientSecret"];

                    if (!string.IsNullOrEmpty(keyVaultEndpoint) && !string.IsNullOrEmpty(keyVaultClientId) && !string.IsNullOrEmpty(keyVaultClientSecret))
                    {
                        config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClientId, keyVaultClientSecret, new DefaultKeyVaultSecretManager());
                    }
                }
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Step 3 : Use in Controller or Business layer ๐Ÿ“

public class TestController : ControllerBase
{
    #region Members

    private readonly Settings _settings;
    private readonly IAzureKeyVaultService _azureKeyVaultService;
    private readonly IConfiguration _configuration;

    #endregion

    #region Ctor

    public TestController(IAzureKeyVaultService azureKeyVaultService, IConfiguration configuration, IOptions<Settings> options)
    {
        _azureKeyVaultService = azureKeyVaultService;
        _configuration = configuration;
        _settings = options.Value;
    }

    #endregion

    #region Methods

    /// <summary>
    /// Get Settings (From Azure Key Vault - Specific setting)
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("get-settings-from-azure-key-vault")]
    public async Task<IActionResult> GetSpecificSettings()
    {
        var appName = await _azureKeyVaultService.GetSecret("Settings__AppName");
        var language = await _azureKeyVaultService.GetSecret("Settings__Language");
        var messages = await _azureKeyVaultService.GetSecret("Settings__Messages");

        var settings = new Settings
        {
            AppName = appName,
            Language = language,
            Messages = messages
        };

        return Ok(settings);
    }

    /// <summary>
    /// Get Settings
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("get-settings")]
    public IActionResult GetSettings()
    {
        var settings = _settings;

        return Ok(settings);
    }

    #endregion
}

Give a Star! โญ

Feel free to request an issue on github if you find bugs or request a new feature. Your valuable feedback is much appreciated to better improve this project. If you find this useful, please give it a star to show your support for this project.

Support โ˜Ž๏ธ

Reach out to me at one of the following places!

Author ๐Ÿ‘ฆ

Connect with me
Linkedin Portfolio Medium GitHub NuGet Microsoft Twitter Facebook Instagram
linkedin Portfolio medium github nuget microsoft twitter facebook instagram

Donate ๐Ÿ’ต

If you find this project useful โ€” or just feeling generous, consider buying me a beer or a coffee. Cheers! ๐Ÿป โ˜•

PayPal BMC Patreon
PayPal Buy Me A Coffee Patreon

License ๐Ÿ”’

This project is licensed under the MIT License - see the LICENSE file for details.