0
votes

I'm trying to leverage the Azure Key Vault REST APIs. I've written a small snippet of code to try to get a key:

private static async Task<object> GetKey(string uri, string token)
{
        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
        HttpResponseMessage resp = await client.GetAsync(uri);

        return resp.Content.ReadAsStringAsync().Result;
}

I'm calling it with

var test = GetKey(
            @"https://<myVault>.vault.azure.net/keys/Test/1?api-version=2016-10-01",
            token
        );

where "Test" is the name of key in . I believe that my access token is correct as I am able to get a list of Vaults that are in Azure. I'm not sure what is going wrong.

My API Registration in Azure has full access to the Key Vault, and is listed as an owner in AAD. The key vault is listed on all networks, even public. Interestingly though, if I use the "try it" feature in the azure documentation with the same parameters, I get a 404 response which I believe could be part of the issue?

Is it possible I need to authenticate to a different resource since this isn't a management API?

1

1 Answers

0
votes

The error stemmed from the last question I posed. The resource for the Rest API for the Azure Key Vault is https://vault.azure.net/ whereas I was using https://management.azure.com/. However, using a direct HTTP request to this URL did not provide a token that gave me the proper access. I ended up using the SDK to communicate with Azure Key Vault, namely:

private async Task<string> GetAccessTokenAsync(string authority, string resource, string scope)
{
        var appCredentials = new ClientCredential(applicationId, clientSecret);
        var context = new AuthenticationContext(authority, TokenCache.DefaultShared);

        var result = await context.AcquireTokenAsync(resource, appCredentials);

        return result.AccessToken;
}

where it's called from the SDK method as:

public async Task<string> GetKeyAsync(string vaultUrl, string vaultKey)
{
        var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessTokenAsync), new HttpClient());
        var secret = await client.GetKeyAsync(vaultUrl, vaultKey);

        return secret.Key.ToString();
}

which is called from main by

string res = (new Program()).GetSecretAsync("https://<myVault>.vault.azure.net/", keyName).Result;

Also note that clientSecret and applicationId are class properties.