locked
Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: Operation returned an invalid status code Forbidden.. RRS feed

  • Question

  • Hi,

    Following code throws exception is both cases : when I run locally and when I run on Azure.

    What is missing here ?

    Code:

    --------

            static string clientId = "<Client Id>";
            static string clientSecret = "<Client Secret>";

            [FunctionName("TestFunction01")]
            public static async System.Threading.Tasks.Task RunAsync([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
            {
                try
                {
                    var azureServiceTokenProvider = new AzureServiceTokenProvider();
                    var keyVaultClient = new KeyVaultClient(GetAccessTokenAsync, new HttpClient());
                    var cacheSecret = await keyVaultClient.GetSecretAsync("https://<keyvaultname>.vault.azure.net", "TestKeyToBeDeleted");
                    string connectionString = cacheSecret.Value;

                    log.LogInformation($"Secret = {connectionString}");
                }
                catch(Exception exp)
                {
                    log.LogInformation($"Exception = {exp.ToString()}");
                }
            }

            public static async Task<string> GetAccessTokenAsync(string authority, string resource, string scope)
            {
                var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
                ClientCredential credential = new ClientCredential(clientId, clientSecret);
                AuthenticationResult result = await context.AcquireTokenAsync(resource, credential);
                if (result == null)
                    logShared.LogInformation($"Failed to obtain the JWT token");

                return result.AccessToken;
            }

    Exception:

    --------------

    Exception = Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: Operation returned an invalid status code 'Forbidden'
       at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretWithHttpMessagesAsync(String vaultBaseUrl, String secretName, String secretVersion, Dictionary`2 customHeaders, CancellationToken cancellationToken)
       at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretAsync(IKeyVaultClient operations, String vaultBaseUrl, String secretName, CancellationToken cancellationToken)

    Thank you.


    • Edited by Ajay13579 Monday, June 24, 2019 5:13 PM
    Monday, June 24, 2019 5:13 PM

All replies

  • By looking at the error message it looks like a permissions issue.  Can you please validate if you have added permissions in the Key Vault for the registered application. 

    Can you verify if you added your registered application or user to Access policies control blade of Azure Key Vault.

     
    Monday, June 24, 2019 11:55 PM
  • I'd say that the solution proposed by @SaurabhSharma-MSFT is too heavy handed as it grants too many permissions to the Registered App.  I'm not even certain that it fixes the problem. 

    I ran into this as well and fixed it without granting the Registered App any API Permission in the Active Directory blade.  In the Key Vault's "Access Control (IAM)" blade, the Registered App is not an Owner but only Contributor (inherited through the Subscription).

    You need something along these lines: https://stackoverflow.com/questions/40025598/azure-key-vault-access-denied?rq=1 

    My own problem was that in the callstack of an IKeyResolver instance I was getting the very same "KeyVaultErrorException Operation returned an invalid status code 'Forbidden'" thrown by the KeyVaultClient.UnwrapKeyWithHttpMessagesAsync method.  The context is that a TableOperation.Retrieve is using the IKeyResolver from the context of a TableEncryptionPolicy instance.  So, it's clearly a Table field decryption operation.  In the Key Vault instance's Access Policies blade, I had only Get and List for Key Permissions.  I added the "Unwrap Key" permission and the problem went away.  It should be no surprise that granting the "Unwrap Key" permission fixed an exception thrown by an UnwrapKeyWithHttpMessagesAsync method ;-)


    Thank you, eugen_nw

    Tuesday, October 15, 2019 10:57 PM