/// <summary> /// Transforms Azure KeyVault macros into their respective values. /// </summary> /// <param name="configurationBuilder"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task <IConfigurationBuilder> TransformKeyVaultMacrosAsync(this IConfigurationBuilder configurationBuilder, CancellationToken cancellationToken = default) { var needsTransformation = GatherTransformablePairs(configurationBuilder); // Lookup & Transform var azureServiceTokenProvider = new AzureServiceTokenProvider(); var callback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(callback, new HttpClient()); var transformedMacros = new Dictionary <string, string>(); var lookupTasks = new Task <SecretBundle> [needsTransformation.Count]; for (var index = 0; index < needsTransformation.Count; index++) { lookupTasks[index] = keyVaultClient.GetSecretAsync(needsTransformation[index].Value, cancellationToken); } await Task.WhenAll(lookupTasks).ConfigureAwait(false); for (var index = 0; index < needsTransformation.Count; index++) { transformedMacros.Add(needsTransformation[index].Key, lookupTasks[index].Result.Value); } configurationBuilder.AddInMemoryCollection(transformedMacros); return(configurationBuilder); }
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); var config = builder.Build(); string keyVaultUrl = config["keyVaultUrl"]; if (string.IsNullOrWhiteSpace(keyVaultUrl)) { throw new InvalidOperationException("Could not find keyVaultUrl configuration setting."); } var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(keyVaultCallback); builder.AddAzureKeyVault(keyVaultUrl, keyVaultClient, new DefaultKeyVaultSecretManager()); try { Configuration = builder.Build(); CurrentEnvironment = env; } catch (Exception ex) { new TelemetryClient().TrackException(ex); new LoggerFactory().CreateLogger("Exception").LogError("Exception '{0}' while building configuration: {1}", ex.GetType().Name, ex.Message); Configuration = config; } }
public static IServiceCollection AddKeyVault(this IServiceCollection services, IConfiguration configuration) { var vaultSettings = new VaultSettings(); configuration.Bind("Vault", vaultSettings); KeyVaultClient.AuthenticationCallback callback = async(authority, resource, scope) => { var authContext = new AuthenticationContext(authority); var clientCertFile = Path.Combine( Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".secrets"), vaultSettings.ClientCertFile); var certificate = new X509Certificate2(clientCertFile); var clientCred = new ClientAssertionCertificate(vaultSettings.ClientId, certificate); var result = await authContext.AcquireTokenAsync(resource, clientCred); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return(result.AccessToken); }; var kvClient = new KeyVaultClient(callback); services.AddSingleton <IKeyVaultClient>(kvClient); return(services); }
public async Task <int> ExecuteAsync() { Console.WriteLine($"Verifying {VaultOptions.VaultUrl} Key Vault"); var azureServiceTokenProvider = new AzureServiceTokenProvider(); var authCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authCallback); var result = await keyVaultClient.GetSecretsAsync(VaultOptions.VaultUrl); while (true) { foreach (Microsoft.Azure.KeyVault.Models.SecretItem item in result) { var secret = await keyVaultClient.GetSecretAsync(item.Id); Console.WriteLine($" - {item.Id}"); Console.WriteLine($" {secret.Value}"); } if (result.NextPageLink == null) { break; } result = await keyVaultClient.GetSecretsNextAsync(result.NextPageLink); } return(0); }
/// <inheritdoc /> public void Configure(IWebHostBuilder builder) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var authenticationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authenticationCallback); var baseConfiguration = HostingStartupConfigurationExtensions.GetBaseConfiguration(); builder.ConfigureServices((context, collection) => { var configuration = new ConfigurationBuilder() .AddConfiguration(baseConfiguration) .AddConfiguration(context.Configuration) .Build(); if (configuration.IsEnabled(HostingStartupName, DataProtectionFeatureName) && configuration.TryGetOption(HostingStartupName, DataProtectionKeyName, out var protectionKey)) { AddDataProtection(collection, keyVaultClient, protectionKey); } }); if (baseConfiguration.IsEnabled(HostingStartupName, ConfigurationFeatureName) && baseConfiguration.TryGetOption(HostingStartupName, ConfigurationVaultName, out var vault)) { builder.ConfigureAppConfiguration((context, configurationBuilder) => { AddConfiguration(configurationBuilder, keyVaultClient, vault); }); } }
/// <summary> /// /// </summary> /// <param name="keyIdentifier"></param> /// <param name="algorithm">A valid and supported <see cref="JsonWebKeySignatureAlgorithm"/> value. Note: <see cref="JsonWebKeySignatureAlgorithm.RSNULL"/> is not supported.</param> /// <param name="keyVaultAuthenticationCallback"></param> /// <exception cref="ArgumentException">RSNULL is not allowed in this scenario.</exception> /// <exception cref="ArgumentException">Supplied value is not a currently supported JsonWebKeySignatureAlgorithm value.</exception> public AzureKeyVaultSignatureProvider( string keyIdentifier, string algorithm, KeyVaultClient.AuthenticationCallback keyVaultAuthenticationCallback) : this(keyIdentifier, algorithm, new KeyVaultClient(keyVaultAuthenticationCallback)) { }
/// <summary> /// Use Managed Service Identity to delegate authentication with Azure AD to Azure /// </summary> public static KeyVaultAuthenticationBuilder UseManagedServiceIdentity() { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var authenticationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); return(new KeyVaultAuthenticationBuilder(authenticationCallback)); }
public async Task <ActionResult> Secret() { // // When a call is made to the KeyVaultClient to retrieve a secret, key, or certificate (see GetSecretAsync below) // the SDK will execute a callback delegate to obtain an identity token for the identity with which it will // access the key vault. // // When an instance of AzureServiceTokenProvider is created with no constructor parameters the managed identity of // the host web app is used. // // Here, we setup a callback to obtain a token for the Managed Identity of the application, // i.e. AzureServiceTokenProvider.KeyVaultTokenCallback // AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); KeyVaultClient.AuthenticationCallback callback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); KeyVaultClient keyVaultClient = new KeyVaultClient(callback); // Get key vault details from the application's configuration string keyVaultEndPoint = this.config["KeyVaultEndPoint"]; // Must be the base URL of the keyvault; i.e. https://{key-vault-name}.vault.azure.net/ string keyVaultSecretName = this.config["KeyVaultSecretName"]; // Using the KeyVaultClient, fetch the secret from the vault. // This will first obtain an identity token using the callback above, and using that token will then retrieve the secret. SecretBundle secretBundle = await keyVaultClient.GetSecretAsync(keyVaultEndPoint, keyVaultSecretName); ViewBag.Message = secretBundle.Value; return(View()); }
public IKeyVaultClient CreateKeyVaultClient(string connectionString) { var azureServiceTokenProvider = new AzureServiceTokenProvider(connectionString); var authCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); return(new KeyVaultClient(authCallback)); }
public static KeyVaultClient InitKeyVault(string keyVaultAddress, string clientID, string clientSecret) { //var azureServiceTokenProvider = new AzureServiceTokenProvider(); // way 1 , follow this https://docs.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-3.0#secret-storage-in-the-production-environment-with-azure-key-vault // var keyVaultClient = new KeyVaultClient( // new KeyVaultClient.AuthenticationCallback( // azureServiceTokenProvider.KeyVaultTokenCallback)); //way 2 , follow to https://c-sharx.net/read-secrets-from-azure-key-vault-in-a-net-core-console-app var authenticationCallBack = new KeyVaultClient.AuthenticationCallback( // get token async(string authority, string resource, string scope) => { //GetCredential() var credential = new ClientCredential(clientID, clientSecret); var authContext = new AuthenticationContext(authority); AuthenticationResult result = await authContext.AcquireTokenAsync(resource, credential); if (result == null) { throw new InvalidOperationException("Failed to retrieve JWT token"); } return(result.AccessToken); } ); var keyVaultClient = new KeyVaultClient(authenticationCallBack); // Calling GetSecretAsync will trigger the authentication code above and eventually // retrieve the secret which we can then read. var secretBundle = keyVaultClient.GetSecretAsync(keyVaultAddress, "secretKey"); return(keyVaultClient); }
/// <summary> /// /// </summary> /// <param name="user"></param> User ID / Application (client) ID /// <param name="password"></param> User PW / Client secrets /// <returns></returns> /// <example> /// KeyVaultClient client = GetKeyVaultClient("[Application (client) ID]", "[Client secrets]"); /// </example> private KeyVaultClient GetKeyVaultClient(string user, string password) { try { // Define the KeyVaultClient.AuthenticationCallback Delegate var authCallBackDel = new KeyVaultClient.AuthenticationCallback(async(string authority, string resource, string scope) => { var context = new AuthenticationContext(authority, TokenCache.DefaultShared); ClientCredential clientCred = new ClientCredential(user, password); var authResult = await context.AcquireTokenAsync(resource, clientCred); return(authResult.AccessToken); }); // Create the Key Vault Client KeyVaultClient client = new KeyVaultClient(authCallBackDel); logger.Debug($"GetKeyVaultClient: Successfully created new Key Vault Client"); return(client); } catch (Exception ex) { logger.Error($"GetKeyVaultClient: Failed to create Key Vault Client\n{ex.Message}\n{ex.StackTrace}"); throw ex; } }
public TemporaryExposureKeyService(IConfiguration config, ITemporaryExposureKeyRepository tek, ITemporaryExposureKeyExportRepository tekExport, ILogger <TemporaryExposureKeyService> logger) { AppBundleId = config["AppBundleId"]; AndroidPackage = config["AndroidPackage"]; TekExportBlobStorageConnectionString = config["TekExportBlobStorage"]; TekExportBlobStorageContainerPrefix = config["TekExportBlobStorageContainerPrefix"]; Region = config["Region"]; TekExportKeyVaultKeyUrl = config["TekExportKeyVaultKeyUrl"]; TekRepository = tek; TekExportRepository = tekExport; Logger = logger; var sig = new SignatureInfo(); sig.AppBundleId = AppBundleId; sig.AndroidPackage = AndroidPackage; sig.SignatureAlgorithm = "ECDSA"; SigInfo = sig; StorageAccount = CloudStorageAccount.Parse(TekExportBlobStorageConnectionString); BlobClient = StorageAccount.CreateCloudBlobClient(); BlobContainerName = $"{TekExportBlobStorageContainerPrefix}{Region}".ToLower(); AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); var credentialCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); KeyVault = new KeyVaultClient(credentialCallback); }
public TemporaryExposureKeySignService(IConfiguration config) { TekExportKeyVaultKeyUrl = config["TekExportKeyVaultKeyUrl"]; AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); var credentialCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); KeyVault = new KeyVaultClient(credentialCallback); }
private static KeyVaultClient AuthenticateClient() { var tokenProvider = new AzureServiceTokenProvider(); var authenticationCallback = new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authenticationCallback); return keyVaultClient; }
public SqlColumnEncryptionAzureKeyVaultProvider( KeyVaultClient.AuthenticationCallback authenticationCallback) : this(authenticationCallback, new string[1] { "vault.azure.net" }) { }
/// <summary> /// Creates a new instance of <see cref="AzureKeyVaultConfigurationOptions"/>. /// </summary> /// <param name="vault">The Azure KeyVault uri.</param> public AzureKeyVaultConfigurationOptions(string vault) : this() { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var authenticationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); Vault = vault; Client = new KeyVaultClient(authenticationCallback); }
/// <inheritdoc /> /// <summary> /// This method is invoked once, to allow the cmdlet initialize all of its dependencies /// </summary> protected override void BeginProcessing() { AzureServiceTokenProvider authentication = new AzureServiceTokenProvider(); KeyVaultClient.AuthenticationCallback authenticationCallback = new KeyVaultClient.AuthenticationCallback(authentication.KeyVaultTokenCallback); _keyVaultClient = new KeyVaultClient(authenticationCallback); }
/// <summary> /// Constructor that takes a callback function to authenticate to AAD. This is used by KeyVaultClient at runtime /// to authenticate to Azure Key Vault. /// </summary> /// <param name="authenticationCallback">Callback function used for authenticating to AAD.</param> public SqlColumnEncryptionAzureKeyVaultProvider(KeyVaultClient.AuthenticationCallback authenticationCallback) { if (authenticationCallback == null) { throw new ArgumentNullException("authenticationCallback"); } KeyVaultClient = new KeyVaultClient(authenticationCallback); }
public SqlColumnEncryptionAzureKeyVaultProvider( KeyVaultClient.AuthenticationCallback authenticationCallback, string trustedEndPoint) : this(authenticationCallback, new string[1] { trustedEndPoint }) { }
static async Task Main(string[] args) { var tokenProvider = new AzureServiceTokenProvider(); var callback = new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback); var client = new KeyVaultClient(callback); var secret = await client.GetSecretAsync(KeyVaultHelper.GetVaultUrl(VAULT_NAME), SECRET_NAME); Console.WriteLine($"The secret value I retrieved from Key Vault: {secret.Value}!"); }
public static IConfigurationBuilder AddAMyAzureKeyVault(this IConfigurationBuilder configurationBuilder) { var vaultEndpoint = "https://benjamintestvault.vault.azure.net/"; var azureServiceTokenProvider = new AzureServiceTokenProvider(); var defaultKeyVaultSecretManager = new DefaultKeyVaultSecretManager(); var authentificationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authentificationCallback); return(configurationBuilder.AddAzureKeyVault(vaultEndpoint, keyVaultClient, defaultKeyVaultSecretManager)); }
public static IConfigurationRoot AddConfiguration(this IServiceCollection services, Assembly assembly) { var providers = new List <IConfigurationProvider>(); var configServiceDescriptors = services.Where(descriptor => descriptor.ServiceType == typeof(IConfiguration)) .ToList(); foreach (var descriptor in configServiceDescriptors) { if (!(descriptor.ImplementationInstance is IConfigurationRoot existingConfiguration)) { continue; } providers.AddRange(existingConfiguration.Providers); services.Remove(descriptor); } var serviceProvider = services.BuildServiceProvider(); var executionContext = serviceProvider.GetService <IOptions <ExecutionContextOptions> >().Value; var builder = new ConfigurationBuilder() .SetBasePath(executionContext.AppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); var aspCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.Equals(aspCoreEnvironment, "Development", StringComparison.InvariantCultureIgnoreCase)) { builder.AddUserSecrets(assembly, optional: true); } else { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var authenticationCallback = new KeyVaultClient.AuthenticationCallback( azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authenticationCallback); var defaultKeyVaultSecretManager = new DefaultKeyVaultSecretManager(); builder.AddAzureKeyVault("https://socialnetworkapp-0-kv.vault.azure.net/", keyVaultClient, defaultKeyVaultSecretManager); } var config = builder.Build(); providers.AddRange(config.Providers); var configurationRoot = new ConfigurationRoot(providers); services.AddSingleton <IConfiguration>(configurationRoot); return(configurationRoot); }
public TemporaryExposureKeySignService( IConfiguration config, ILogger <TemporaryExposureKeySignService> logger) { Logger = logger; TekExportKeyVaultKeyUrl = config.TekExportKeyVaultKeyUrl(); AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); var credentialCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); KeyVault = new KeyVaultClient(credentialCallback); }
/// <summary> /// Creates a new instance of <see cref="AzureKeyVaultConfigurationOptions"/>. /// </summary> /// <param name="vault">Azure KeyVault uri.</param> /// <param name="clientId">The application client id.</param> /// <param name="certificate">The <see cref="X509Certificate2"/> to use for authentication.</param> public AzureKeyVaultConfigurationOptions( string vault, string clientId, X509Certificate2 certificate) : this() { KeyVaultClient.AuthenticationCallback authenticationCallback = (authority, resource, scope) => GetTokenFromClientCertificate(authority, resource, clientId, certificate); Vault = vault; Client = new KeyVaultClient(authenticationCallback); }
private KeyVaultClient AuthenticateClient() { // Unfortunately the default azureAdInstance is hardcoded to a value rather than null, avoid having to hard code the value here too. var tokenProvider = _azureAdInstance == null ? new AzureServiceTokenProvider(_connectionString) : new AzureServiceTokenProvider(_connectionString, _azureAdInstance); var authenticationCallback = new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authenticationCallback); return(keyVaultClient); }
/// <summary> /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from the Azure KeyVault. /// </summary> /// <param name="configurationBuilder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="vault">Azure KeyVault uri.</param> /// <param name="manager">The <see cref="IKeyVaultSecretManager"/> instance used to control secret loading.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddAzureKeyVault( this IConfigurationBuilder configurationBuilder, string vault, IKeyVaultSecretManager manager) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var authenticationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authenticationCallback); return(AddAzureKeyVault(configurationBuilder, vault, keyVaultClient, manager)); }
public static IServiceCollection AddKeyVault(this IServiceCollection services, IConfiguration configuration) { var vaultSettings = new VaultSettings(); configuration.Bind(nameof(VaultSettings), vaultSettings); var loggerFactory = services.BuildServiceProvider().GetService <ILoggerFactory>(); var logger = loggerFactory?.CreateLogger <VaultSettings>(); logger?.LogInformation($"retrieving vault settings: vaultName={vaultSettings.VaultName}"); KeyVaultClient.AuthenticationCallback callback = async(authority, resource, scope) => { var authContext = new AuthenticationContext(authority); if (!string.IsNullOrEmpty(vaultSettings.ClientSecretFile)) { var clientSecretFile = GetSecretOrCertFile(vaultSettings.ClientSecretFile, logger); var clientSecret = File.ReadAllText(clientSecretFile); var credential = new ClientCredential(vaultSettings.ClientId, clientSecret); var result = await authContext.AcquireTokenAsync(resource, credential); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return(result.AccessToken); } else { var clientCertFile = GetSecretOrCertFile(vaultSettings.ClientCertFile, logger); var certificate = new X509Certificate2(clientCertFile); Console.WriteLine($"Authenticate client {vaultSettings.ClientId} with cert: {certificate.Thumbprint}"); var clientCred = new ClientAssertionCertificate(vaultSettings.ClientId, certificate); Console.WriteLine($"Authenticating..."); var result = await authContext.AcquireTokenAsync(resource, clientCred); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return(result.AccessToken); } }; var kvClient = new KeyVaultClient(callback); services.AddSingleton <IKeyVaultClient>(kvClient); return(services); }
public static IConfigurationBuilder AddAzureKeyVaultWithNameRefSupport( this IConfigurationBuilder builder, string azureKeyVaultUrl = null, IKeyVaultGateway keyVaultGateway = null) { if (keyVaultGateway == null) { var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultAuthCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(keyVaultAuthCallback); keyVaultGateway = new AzureKeyVaultGateway(keyVaultClient); } return(builder.Add(new ConfigurationSource(builder.Build(), azureKeyVaultUrl, keyVaultGateway))); }
public static IHostBuilder CreateHostBuilder(string[] args) => Host .CreateDefaultBuilder(args) .ConfigureAppConfiguration((webHostBuilderContext, configurationBuilder) => { var vaultEndpoint = "https://benjamintestvault.vault.azure.net/"; var azureServiceTokenProvider = new AzureServiceTokenProvider(); var defaultKeyVaultSecretManager = new DefaultKeyVaultSecretManager(); var authentificationCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authentificationCallback); configurationBuilder.AddAzureKeyVault(vaultEndpoint, keyVaultClient, defaultKeyVaultSecretManager); }) .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup <Startup>());
public TemporaryExposureKeySignService( IConfiguration config, ILogger <TemporaryExposureKeySignService> logger) { Logger = logger; Logger.LogInformation($"{nameof(TemporaryExposureKeySignService)} constructor"); TekExportKeyVaultKeyUrl = config.TekExportKeyVaultKeyUrl(); VerificationKeyId = config.VerificationKeyId(); VerificationKeyVersion = config.VerificationKeyVersion(); AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); var credentialCallback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); KeyVault = new KeyVaultClient(credentialCallback); }