ericpap
ericpap

Reputation: 2937

Unable to retrieve Key Vault Secret from Docker App Service in .NET Core

I'm running a Web API that use NET Core 3.1 from Azure App service in a docker container, and struggling to obtain a secret key from Key Vault Service. My code looks fine, y get no errors but the response is always empty. This is my Startup initializacion:

public Startup(IWebHostEnvironment env)
    {   
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();

        this.bIsDevelopemnt = env.IsDevelopment();           

        Configuration = builder.Build();

        var azureServiceTokenProvider = new AzureServiceTokenProvider();
        KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

        builder.AddAzureKeyVault(
            $"https://{Configuration.GetSection("KeyVaultName").Value}.vault.azure.net/",
            keyVaultClient,
            new DefaultKeyVaultSecretManager());           
    }

And i'm using this controller to test the results, which returns null in all three cases:

[HttpGet("/secrets")]
    public IActionResult getSecrets()
    {
        try
        {

            var value = configuration["tokenKey"];
            var value2 = configuration["OhmioAPI:tokenKey"];
            var value3 = configuration["OhmioAPI--tokenKey"];

            return Ok(new { orign = "pirulo", key1 = value, key2 = value2, key3 = value3 });
        }
        catch (Exception e)  {
            return NotFound(e.Message);
        }            
    }

What I have try/done: * Create the Key Vault Store and secrets * Create an Identity ID for my App * Add permission to get/list secrets from the key Store

Any Ideas?

Upvotes: 0

Views: 2529

Answers (1)

Gaurav Kumar
Gaurav Kumar

Reputation: 156

The easiest way would be to use Key Vault Reference. See: https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references

Major Steps:

  • Enable MSI on Azure WebApp
  • Allow the WebApp to access the KeyVault via Access Policies in KeyVault
  • Add an application say, test with the value: @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931) [Change the secretUri as per the secret's URI which you are trying to access]
  • That's it. The WebApp will automatically get the secret from the KeyVault, which you can now access as if they were environment variable.
  • You could echo the application setting (TEST in our case) to check if the value has been set

Upvotes: 1

Related Questions