Search code examples
azureazure-storageazure-keyvault

Azure Storage UseDevelopmentStorage=true when using KeyVault


I have configured my API to get the Azure Storage connection string from Azure KeyVault using Managed Identity.

Now the problem is that when I run the code locally in Visual Studio, it no longer uses the connection string from the appsettings.development.json which was "StorageAccount": "UseDevelopmentStorage=true"

Therefore I can't use the emulator when running locally.

I have created the following condition in my controller to work around this issue :

    public FileController(IConfiguration configuration, IWebHostEnvironment env)
    {
        this.configuration = configuration;

        if (env.IsDevelopment())
        {
            conn = this.configuration.GetConnectionString("StorageAccount");

        }
        else
        {
            conn = this.configuration["StorageConnectionString"];

        }
    }

Is this the proper way to do it ?


Solution

  • In local, if your ASPNETCORE_ENVIRONMENT set to Development, then it will read you local storage account like UseDevelopmentStorage=true.

    When you publish to azure, it will use your webapp's MSI to get the connectionstring from key vault.

    For more details, you could refer to the following code:

    private IConfiguration _configuration;
    private IWebHostEnvironment _env;
    
    public WeatherForecastController(IConfiguration configuration, IWebHostEnvironment env)
    {
        _configuration = configuration;
        _env = env;
    }
    
    if (_env.IsDevelopment())
    {
        con = _configuration.GetSection("StorageAccount").Value;
    }
    else
    {
        AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
        var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
        con = keyVaultClient.GetSecretAsync("https://xxxx.vault.azure.net/secrets/xxxx").GetAwaiter().GetResult().Value;
    
    }