azureasp.net-core.net-5azure-keyvaultasp.net-core-5.0

How to fix "Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: 'Operation returned an invalid status code 'NotFound''"


I am trying to get the values from my Azure Key vault in ASP.Net Core 5 Web API application. But I'm faced with this issue:

enter image description here

I have added this code in Program.cs file

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
        .ConfigureAppConfiguration((context, config) =>
        {
            var builtConfig = config.Build();
            var vaultName = builtConfig["keyvault"];

            var keyVaultClient = new KeyVaultClient(
                async (authoriy, resource, scope) =>
                {
                    var credential = new DefaultAzureCredential(false);
                    var token = credential.GetToken(
                            new TokenRequestContext(
                                new[] {"https://vault.azure.net/.default" }
                                )
                        );
                    return token.Token;
                });
            config.AddAzureKeyVault(
                vaultName,
                keyVaultClient,
                new DefaultKeyVaultSecretManager());
        });

In appsettings.json file, I gave the key-vault URL like this.

"Keyvault": "https://<<vaultName>>.vault.azure.net/.default"

And I have created the Secret with the name "StorageConnectionString" I am using in my Class in the Azure Key-vault.

public BlobContainerProvider(IConfiguration configuration) 
    {
        
        string connectionString = configuration.GetValue<string>("StorageConnectionString");

        blobServiceClient = new BlobServiceClient(connectionString);
    }

Solution

  • I found the issue, It is actually in appsettings.json

    I have mentioned it as

    "Keyvault": "https://<<vaultName>>.vault.azure.net/.default"
    

    Whereas ".default" in the URL should not be placed.

    So Generally, such a type of error is thrown if we have placed an unavailable key-vault URL.

    @Gaurav Mantri, Thanks for pointing this out in the comments.