0
votes

I have implemented Key Vault access token generator using below codebase:

private async Task<string> GetStaticToken(string authority, string resource)
{
    var authContext = new AuthenticationContext(authority);
    var credential = new ClientCredential(_appSettings.ClientId, _appSettings.ClientSecret);
    AuthenticationResult result = await authContext.AcquireTokenAsync(resource, credential);
    return result.AccessToken;
}

I know how to use this token into Authorization header and get the secret values using Rest API call. But can we use the same AccessToken string into below code base:

var builder = new ConfigurationBuilder();
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));                            
builder.AddAzureKeyVault($"https://{myVaultName}.vault.azure.net/", keyVaultClient, new DefaultKeyVaultSecretManager());
Configuration = builder.Build();

Here is it possible to re-use AccessToken string value, while creating KeyVaultClient? Something like below:

var tokenValue = GetStaticToken (authority, resource);
var keyVaultClient = new KeyVaultClient(tokenValue); 

Basically I would like to generate token at once and reuse string everywhere, even outside my application scope.

Note: I am aware that token will come with expiration time duration. That time GetToken will be called again.

1

1 Answers

4
votes

Well, you can make a callback that returns that token:

var kvClient = new KeyVaultClient((authority, resource, scope) => Task.FromResult(tokenValue));

This simply replaces the call to get a token with an already completed Task with the token in it.