Skip to content

Commit

Permalink
add KV extension method for service principal
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivan Gavryliuk committed Jan 23, 2019
1 parent 5197db2 commit f4a48a1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace Config.Net.Azure.KeyVault
{
Expand All @@ -25,6 +28,31 @@ public static AzureKeyVaultConfigStore CreateWithManagedIdentity(Uri vaultUri)
return new AzureKeyVaultConfigStore(vaultUri, client);
}

public static AzureKeyVaultConfigStore CreateWithPrincipal(Uri vaultUri, string azureAadClientId, string azureAadClientSecret)
{
var credential = new ClientCredential(azureAadClientId, azureAadClientSecret);

var client = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback( (authority, resource, scope) => GetAccessToken(authority, resource, scope, credential) ),
GetHttpClient());

return new AzureKeyVaultConfigStore(vaultUri, client);
}

private static async Task<string> GetAccessToken(string authority, string resource, string scope, ClientCredential credential)
{
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);

AuthenticationResult result = await context.AcquireTokenAsync(resource, credential);

return result.AccessToken;
}

private static HttpClient GetHttpClient()
{
return new HttpClient();
}

public bool CanRead => true;

public bool CanWrite => false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,14 @@ public static ConfigurationBuilder<TInterface> UseAzureKeyVaultWithManagedIdenti

return builder;
}

public static ConfigurationBuilder<TInterface> UseAzureKeyVaultWithServicePrincipal<TInterface>(
this ConfigurationBuilder<TInterface> builder, Uri vaultUri, string clientId, string clientSecret) where TInterface : class
{
builder.UseConfigStore(AzureKeyVaultConfigStore.CreateWithPrincipal(vaultUri, clientId, clientSecret));

return builder;
}

}
}

0 comments on commit f4a48a1

Please sign in to comment.