CrazyCoder
CrazyCoder

Reputation: 2378

Exception raised while accessing keyvault in Azure through C#

I had below code to fetch key vault secrets in Azure:

   var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
    var sec = await kv.GetSecretAsync(ConfigurationManager.AppSettings["SomeURI"]);
    secretValue = sec.Value ;

In App Config I had:

<add key="SomeURI" value="https://baseURL/KeyName/b75cabsdf45667nhjhe516c674457" />

Since I have been using this many times in my application, I have created a class and called that class. The class looks like this:

public static class KeyVaultFetch
    {
        public async static Task<string> GetCachedSecret(string secretname)
        {           
            try
            {
                string BaseUri =  ConfigurationManager.AppSettings["keyvaultBaseURI"].ToString();

                var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
                var secretbundle = await kv.GetSecretAsync($"{BaseUri}{secretname}").ConfigureAwait(false);
                return secretbundle.Value;
            }
            catch (Exception ex)
            {
                log.Error("Exception raised in GetCachedSecret.");
                log.Error("Exception Details: " + ex.Message);
                log.Error("Inner Exception Details: " + ex.InnerException);
                throw;
            }
        }

        public static async Task<string> GetToken(string authority, string resource, string scope)
        {
            try
            {
                var authContext = new AuthenticationContext(authority);
                ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
                AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
                if (result == null)
                    throw new InvalidOperationException("Failed to obtain the JWT token");
                return result.AccessToken;
            }
            catch (Exception ex)
            {
                log.Error("Exception raised while Getting token : " + ex.Message);
                log.Error("Inner Exception Details: " + ex.InnerException);
                throw;
            }
        }
        
    }

And I have written below line to get the secret every time:

secretValue = await KeyVaultFetch.GetCachedSecret(keyName);

But I'm geeting the below exception , when I run my code :

Exception raised in GetCachedSecret.
Exception Details: Invalid ObjectIdentifier: https://baseURL/. Bad number of segments: 2

What am I doing wrong?

Upvotes: 0

Views: 4471

Answers (1)

juunas
juunas

Reputation: 58723

You should use GetSecretAsync with 2 parameters:

await kv.GetSecretAsync(BaseUri, secretname);

At least that's how it is in our apps :)

Upvotes: 3

Related Questions