Azure KeyVault is an alternative Class library method for operating secrets on NET Core ----- azure Security. KeyVault. Secrets

1, Introduction

We were in the last article Net Core Web project added Nuget package of "Microsoft.Azure.KeyVault" to operate secrets data of Azure KeyVault. Microsoft has abandoned "Microsoft.Azure.KeyVault" Nuget. We recommend you to use "Azure.Security.KeyVault.Secrets".

1) Azure Key Vault confidential client library allows us to safely store and control access to tokens, passwords, API keys and other secrets. The library provides operations of creating, retrieving, updating, deleting, clearing, backing up, restoring and listing secrets and their versions.

2) SecretClient provides synchronous and asynchronous operations in the SDK, allowing the client to be selected according to the use case of the application. After initializing the SecretClient , you can interact with the secrets in Azure Key Vault.

Based on the above two points, we will continue to share the relevant knowledge of Azure Key Vault today and use the new "Azure.Security.KeyVault.Secrets" to operate the secrets of Azure Key Vault.

--------------------I am the dividing line--------------------

1. Azure Kay Vault (I) NET Core Console App to obtain confidential information in the key vault

Introduction to azure key (Vault 2) - Introduction

3. Azure KeyVault (III) through Microsoft Azure. The keyvault class library is in NET Core

4. Azure KeyVault (IV) is an alternative Class library method for operating secrets on NET Core ----- azure Security. KeyVault. Secrets

2, Text

1. Add Nuget package of "Azure.Security.KeyVault.Secrets"

Install using the package management console

Install-Package Azure.Security.KeyVault.Secrets -Version 4.2.0

2. Create the # isecretservice interface and # SecretsService implementation class, as well as the controller method

ISecretsService.cs

public interface ISecretsService
    {
        Task<string> GetSecretsAsync(string key);

        Task<string> SetSecretAsync(string key,string value);

        Task<string> DeleteSecretAsync(string key);
    }

SecrectsService.cs

    public class SecretsService : ISecretsService
    {
        private readonly SecretClient _secretClient;

        public SecretsService(SecretClient secretClient)
        {
            this._secretClient = secretClient;
        }

        public async Task<string> GetSecretsAsync(string key)
        {
            var secret= await _secretClient.GetSecretAsync(key);
            return secret.Value.Value;
        }

        public async Task<string> SetSecretAsync(string key, string value)
        {
            var setSecret= await _secretClient.SetSecretAsync(key, value);
            return setSecret.Value.Value;
        }


        public async Task<string> DeleteSecretAsync(string key)
        {
            var operation= await _secretClient.StartDeleteSecretAsync(key);
            var deleteSecret= await operation.WaitForCompletionAsync();
            await _secretClient.PurgeDeletedSecretAsync(operation.Value.Name);

            return deleteSecret.Value.Value;
        }
    }

HomeController.cs

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly IKeyVaultService _keyVaultService;

        private readonly ISecretsService _secretsService;

        public HomeController(ILogger<HomeController> logger,
            IKeyVaultService keyVaultService,
            ISecretsService secretsService)
        {
            _logger = logger;
            _keyVaultService = keyVaultService;
            _secretsService = secretsService;
        }

        public async Task<IActionResult> Index()
        {
            var list = new List<KeyValueViewModel>();
            list.Add(new KeyValueViewModel() { Key ="cnbate-name", Value = await _keyVaultService.GetSecretByKeyAsync("cnbate-name") });
            list.Add(new KeyValueViewModel() { Key = "cnbate-num", Value = await _keyVaultService.GetSecretByKeyAsync("cnbate-num") });
            list.Add(new KeyValueViewModel() { Key = "cnbate-time", Value = await _keyVaultService.GetSecretByKeyAsync("cnbate-time") });


            return View(list);
        }

        public IActionResult Privacy()
        {
            return View();
        }


        public async Task<IActionResult> Secrets()
        {
            var list = new List<KeyValueViewModel>();
            list.Add(new KeyValueViewModel() { Key = "cnbate-name", Value = await _secretsService.GetSecretsAsync("cnbate-name") });
            list.Add(new KeyValueViewModel() { Key = "cnbate-num", Value = await _secretsService.GetSecretsAsync("cnbate-num") });
            list.Add(new KeyValueViewModel() { Key = "cnbate-time", Value = await _secretsService.GetSecretsAsync("cnbate-time") });

            return View(list);
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }

3. Add the injection of secret service and secret client

services.AddSingleton(new Appsettings(Env.ContentRootPath));
services.AddSingleton(x => new SecretClient(vaultUri: new Uri(Appsettings.app("AzureKeyVault", "Endpoint")), credential: new DefaultAzureCredential()));
services.AddScoped<ISecretsService, SecretsService>();

4. Test whether the new method in Nuget package for obtaining Secrets can normally operate the Secrets data of Azure KeyVault

Press F5 to run the project and obtain all the saved Secrets data

Bingo !!!! success. I will not demonstrate the operation of adding and deleting Secrets. You can download the code for operation by yourself.

3, Ending

The content shared in this article also has a lot of my own understanding. If some understanding is not in place, I hope to forgive you and point out the shortcomings.

reference material: About Azure Key Vault

github: https://github.com/yunqian44/Azure.KeyVault

Author: Allen 

Copyright: please indicate the author and source in the obvious position of the article. If mistakes are found, criticism and correction are welcome.

Keywords: Azure

Added by harkly on Tue, 08 Mar 2022 15:07:00 +0200