public FlowConfigBuilder(FlowDataManager data, IKeyVaultClient keyVaultClient, ConfigGenConfiguration conf, [ImportMany] IEnumerable <IFlowDeploymentProcessor> processors) { FlowData = data; KeyVaultClient = keyVaultClient; Configuration = conf; Processors = processors.OrderBy(p => p.GetOrder()).ToArray(); }
public KeyRotationHelper(ICosmosDbService cosmosDbService, BlobStorageService blobStorageService, IKeyVaultClient keyVaultClient, IConfiguration configuration, ILogger <KeyRotationHelper> logger) { this.cosmosDbService = cosmosDbService; this.blobStorageService = blobStorageService; this.keyVaultClient = keyVaultClient; this.configuration = configuration; this.logger = logger; this.RetryCosmosPolicy = this.GetCosmosRetryPolicy(); this.RetryBlobPolicy = GetBlobRetryPolicy(); }
public SigningController( IWebHostEnvironment environment, IKeyVaultClient keyVaultClient, IConfiguration configuration ) { _rootPath = environment.WebRootPath; _keyVaultClient = keyVaultClient; _keyVaultEndpoint = configuration["KeyVaultEndpoint"]; }
public FlowOperation(FlowDataManager flows, IKeyVaultClient keyvault, FlowConfigBuilder configBuilder, JobOperation jobOpers) { FlowData = flows; JobOperation = jobOpers; ConfigBuilder = configBuilder; KeyVaultClient = keyvault; }
/// <summary> /// Gets the specified entity from the vault. /// </summary> /// <param name="identifier">Identifier of the entity to be retrieved.</param> /// <returns>The value retrieved from the vault.</returns> /// <exception cref="ArgumentException"> /// <paramref name="identifier"/> is empty or null. /// </exception> public async Task <SecureString> GetAsync(string identifier) { DateTime executionTime; Dictionary <string, double> eventMetrics; Dictionary <string, string> eventProperties; SecretBundle bundle; identifier.AssertNotEmpty(nameof(identifier)); try { executionTime = DateTime.Now; using (IKeyVaultClient client = GetAzureKeyVaultClient()) { try { bundle = await client.GetSecretAsync(provider.Configuration.KeyVaultEndpoint, identifier).ConfigureAwait(false); } catch (KeyVaultErrorException ex) { if (ex.Body.Error.Code.Equals(NotFoundErrorCode, StringComparison.CurrentCultureIgnoreCase)) { bundle = null; } else { throw; } } } // Track the event measurements for analysis. eventMetrics = new Dictionary <string, double> { { "ElapsedMilliseconds", DateTime.Now.Subtract(executionTime).TotalMilliseconds } }; // Capture the request for the customer summary for analysis. eventProperties = new Dictionary <string, string> { { "Identifier", identifier } }; provider.Telemetry.TrackEvent("KeyVault/GetAsync", eventProperties, eventMetrics); return(bundle?.Value.ToSecureString()); } finally { bundle = null; eventMetrics = null; eventProperties = null; } }
public RenewalOptionParser( IAzureHelper azureHelper, IKeyVaultClient keyVaultClient, IStorageFactory storageFactory, ILogger logger) { _azureHelper = azureHelper ?? throw new ArgumentNullException(nameof(azureHelper)); _keyVaultClient = keyVaultClient ?? throw new ArgumentNullException(nameof(keyVaultClient)); _storageFactory = storageFactory ?? throw new ArgumentNullException(nameof(storageFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
private TemporaryAzureKeyVaultSecret(IKeyVaultClient client, string keyVaultUri, string secretName) { Guard.NotNull(client, nameof(client)); Guard.NotNullOrWhitespace(keyVaultUri, nameof(keyVaultUri)); Guard.NotNullOrWhitespace(secretName, nameof(secretName)); _client = client; _keyVaultUri = keyVaultUri; Name = secretName; }
public EncryptedBlobAsyncCollector(EncryptedBlobAttribute config, IKeyVaultClient keyVaultClient, IKeyNameProvider keyNameProvider) { _config = config; var cloudBlobClient = CloudStorageAccount.Parse(config.BlobConnectionString).CreateCloudBlobClient(); if (string.IsNullOrWhiteSpace(keyNameProvider.DefaultKey) && config.KeyName is string kn && !string.IsNullOrWhiteSpace(kn)) { keyNameProvider.DefaultKey = kn; } _keyVaultBlobClient = new KeyVaultBlobClient(cloudBlobClient, keyVaultClient, keyNameProvider); }
/// <summary> /// Creates a temporary Azure Key Vault secret, deleting when the <see cref="DisposeAsync"/> is called. /// </summary> /// <param name="client">The client to the vault where the temporary secret should be set.</param> /// <param name="keyVaultUri">The URI of the vault.</param> public static async Task <TemporaryAzureKeyVaultSecret> CreateNewAsync(IKeyVaultClient client, string keyVaultUri) { Guard.NotNull(client, nameof(client)); Guard.NotNullOrWhitespace(keyVaultUri, nameof(keyVaultUri)); var testSecretName = Guid.NewGuid().ToString("N"); var testSecretValue = Guid.NewGuid().ToString("N"); await client.SetSecretAsync(keyVaultUri, testSecretName, testSecretValue); return(new TemporaryAzureKeyVaultSecret(client, keyVaultUri, testSecretName)); }
/// <summary> /// Initializes a new instance of the <see cref="KeyVaultKeyWrapProvider"/> class. /// </summary> /// <param name="key">The <see cref="SecurityKey"/> that will be used for key wrap operations.</param> /// <param name="algorithm">The key wrap algorithm to apply.</param> /// <param name="client">A mock <see cref="IKeyVaultClient"/> used for testing purposes.</param> internal KeyVaultKeyWrapProvider(SecurityKey key, string algorithm, IKeyVaultClient client) { _algorithm = string.IsNullOrEmpty(algorithm) ? throw LogHelper.LogArgumentNullException(nameof(algorithm)) : algorithm; if (key == null) { throw LogHelper.LogArgumentNullException(nameof(key)); } _key = key as KeyVaultSecurityKey ?? throw LogHelper.LogExceptionMessage(new NotSupportedException(key.GetType().ToString())); _client = client ?? new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(_key.Callback)); }
public EncryptedFileContentRepository( string fileStorageKey, CloudBlobClient cloudBlobClient, IKeyVaultClient keyVaultClient, IBlobStorage blobStorage) { _fileStorageKey = fileStorageKey; _cloudBlobClient = cloudBlobClient; _blobStorage = blobStorage; _cloudResolver = new KeyVaultKeyResolver(keyVaultClient); }
public PexaApiTokenQueryHandler( IKeyVaultClient keyVaultClient, PexaApiTokenQuery.Validator validator, IMemoryCache memoryCache, IOptions <WCACoreSettings> optionsAccessor) { _keyVaultClient = keyVaultClient; _validator = validator; _memoryCache = memoryCache; _vaultBaseUrl = optionsAccessor.Value.CredentialAzureKeyVaultUrl; }
private async Task <X509Certificate2> GetCertificateAsync(string identifier, IKeyVaultClient keyVaultClient) { var certificateVersionBundle = await keyVaultClient.GetCertificateAsync(identifier); var certificatePrivateKeySecretBundle = await keyVaultClient.GetSecretAsync(certificateVersionBundle.SecretIdentifier.Identifier); var privateKeyBytes = Convert.FromBase64String(certificatePrivateKeySecretBundle.Value); var certificateWithPrivateKey = new X509Certificate2(privateKeyBytes, (string)null, X509KeyStorageFlags.MachineKeySet); return(certificateWithPrivateKey); }
public static async Task <X509Certificate2> GetX509CertificateAsync(this IKeyVaultClient kvClient, string vaultUrl, string certSecretName) { var bundle = await kvClient.GetSecretAsync(vaultUrl, certSecretName); var bytes = Convert.FromBase64String(bundle.Value); var x509 = new X509Certificate2(bytes); return(x509); }
public static async Task <string?> GetKidByName(this IKeyVaultClient keyVaultClient, EncryptedBlobAttribute config, string keyName, CancellationToken cancellationToken) { KeyBundle?key = null; try { key = await keyVaultClient.GetKeyAsync(config.KeyVaultConnectionString, keyName, cancellationToken); } catch (Microsoft.Azure.KeyVault.Models.KeyVaultErrorException kve) when(kve.Response.StatusCode == System.Net.HttpStatusCode.NotFound) { } if (key is null && config.CreateKeyIfNotExistst is bool c && c && !string.IsNullOrWhiteSpace(keyName) && config.KeyType is { })
public InfoTrackCredentialRepository( IKeyVaultClient keyVaultClient, IOptions <WCACoreSettings> options) { if (options is null) { throw new System.ArgumentNullException(nameof(options)); } this.keyVaultClient = keyVaultClient ?? throw new System.ArgumentNullException(nameof(keyVaultClient)); settings = options.Value; }
public TenantOperations(ITableStorageClient tableStorageClient, IBlobStorageClient blobStorageClient, IAzureManagementClient azureManagementClient, IAppConfigurationClient appConfigurationClient, AppConfig config, IGrafanaClient grafanaClient, IKustoTableManagementClient kustoTableManagementClient, IIdentityGatewayClient identityGatewayClient, IKeyVaultClient keyVaultClient) { this.tableStorageClient = tableStorageClient; this.blobStorageClient = blobStorageClient; this.azureManagementClient = azureManagementClient; this.appConfigurationClient = appConfigurationClient; this.config = config; this.grafanaClient = grafanaClient; this.kustoTableManagementClient = kustoTableManagementClient; this.identityGatewayClient = identityGatewayClient; this.keyVaultClient = keyVaultClient; }
/// <summary> /// Initializes a new instance of the <see cref="KeyVaultSecretsProvider"/> class. /// </summary> /// <param name="secretsProviderOptions">A reference to the secrets provider options.</param> /// <param name="tokenProvider">A reference to the token provider service to use to obtain access to the vault.</param> /// <param name="logger">A logger for this provider.</param> public KeyVaultSecretsProvider( IOptions <KeyVaultSecretsProviderOptions> secretsProviderOptions, ITokenProvider tokenProvider, ILogger logger) { secretsProviderOptions?.Value.ThrowIfNull(nameof(secretsProviderOptions)); tokenProvider.ThrowIfNull(nameof(tokenProvider)); this.BaseUri = new Uri(secretsProviderOptions.Value.VaultBaseUrl); this.keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(tokenProvider.TokenCallback)); this.Logger = logger.ForContext <KeyVaultSecretsProvider>(); }
public AzureKeyVault(IConfigurationRoot configuration) { _configuration = configuration; var tokenProvider = new AzureServiceTokenProvider(); _keyVault = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback)); _keyVaultUrl = _configuration.GetSection("key-vault:url").Value; if (String.IsNullOrEmpty(_keyVaultUrl)) { throw new Exception("Please add the url of the key vault in appsettings.json file as key-vault with property url."); } }
public static async Task <string> GetAccessToken( AadAppSettings settings, KeyVaultSettings vaultSettings = null, IKeyVaultClient kvClient = null) { if (!string.IsNullOrEmpty(settings.ClientCertName)) { if (kvClient == null) { throw new ArgumentNullException(nameof(kvClient)); } if (vaultSettings == null) { throw new ArgumentNullException(nameof(vaultSettings)); } } IConfidentialClientApplication app; if (!string.IsNullOrEmpty(settings.ClientCertName) && vaultSettings != null) { var cert = await kvClient.GetCertificateAsync(vaultSettings.VaultUrl, settings.ClientCertName); var pfx = new X509Certificate2(cert.Cer); app = ConfidentialClientApplicationBuilder.Create(settings.ClientId) .WithCertificate(pfx) .WithAuthority(settings.Authority) .Build(); } else { throw new ArgumentException("Either client secret or cert must be specified", nameof(settings)); } try { var result = await app.AcquireTokenForClient(settings.Scopes).ExecuteAsync(); return(result.AccessToken); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Scope provided is not supported"); Console.ResetColor(); } return(null); }
public AzureKeyVaultKeyManagement(IKeyVaultClient keyVaultClient, IConfiguration configuration) { mKeyVaultClient = keyVaultClient; mKeyVaultName = configuration["KeyManagement:KeyVault:Name"]; mKeyType = configuration["KeyManagement:KeyVault:KeyType"]; if (!short.TryParse(configuration["KeyManagement:KeyVault:KeyLength"], out mKeyLength)) { throw new Exception($"Expected key length int, got {configuration["KeyManagement:KeyVault:KeyLength"]}"); } }
public KeyVaultCertificateStore( IAzureHelper azureHelper, IKeyVaultClient keyVaultClient, string keyVaultName, string resourceGroupName, string certificateName) { _azureHelper = azureHelper ?? throw new ArgumentNullException(nameof(azureHelper)); _keyVaultClient = keyVaultClient ?? throw new ArgumentNullException(nameof(keyVaultClient)); Name = keyVaultName ?? throw new ArgumentNullException(nameof(keyVaultClient)); _resourceGroupName = resourceGroupName ?? throw new ArgumentNullException(nameof(resourceGroupName)); _certificateName = certificateName ?? throw new ArgumentNullException(nameof(keyVaultClient)); }
public WalletService( IKeyVaultClient keyVaultClient, ILogFactory logFactory, string vaultBaseUrl, IWalletRepository walletRepository, int?batchSize = null) { _keyVaultClient = keyVaultClient; _log = logFactory.CreateLog(this); _vaultBaseUrl = vaultBaseUrl; _walletRepository = walletRepository; _batchSize = batchSize ?? DefaultBatchSize; }
/// <summary> /// Initializes static members of the <see cref="KVTests"/> class. /// </summary> static KVTests() { FileSettingsReader = new FileSettingsReader(ConfigurationManager.AppSettings["ConfigRelativePath"] + Path.DirectorySeparatorChar + TestConstants.ConfigFileName); SigningKey = FileSettingsReader.ReadValue(BearerTokenSigningKey); ClientId = FileSettingsReader.ReadValue(EmbeddedSocialClientIdSetting); VaultUrl = FileSettingsReader.ReadValue(SocialPlusVaultUrlSetting); CertThumbprint = FileSettingsReader.ReadValue(SocialPlusCertThumbprint); StoreLoc = StoreLocation.CurrentUser; var cert = new CertificateHelper(CertThumbprint, ClientId, StoreLoc); Client = new AzureKeyVaultClient(cert); TestLog = new Log(LogDestination.Debug, Log.DefaultCategoryName); }
///GENMHASH:6553208EDE6088A698CBA12162179CE6:F1BA2A0D99BABACBDE52E4CA2270EF7E internal VaultImpl(string name, VaultInner innerObject, IKeyVaultManager manager, IGraphRbacManager graphRbacManager) : base(name, innerObject, manager) { this.graphRbacManager = graphRbacManager; this.accessPolicies = new List <AccessPolicyImpl>(); if (innerObject != null && innerObject.Properties != null && innerObject.Properties.AccessPolicies != null) { foreach (var entry in innerObject.Properties.AccessPolicies) { this.accessPolicies.Add(new AccessPolicyImpl(entry, this)); } } this.client = new KeyVaultClientInternal(Manager.RestClient.Credentials, Manager.RestClient.RootHttpHandler, Manager.RestClient.Handlers.ToArray()); }
/// <summary> /// Updates a certificate version. /// </summary> /// <param name="certificateIdentifier">The URL for the certificate.</param> /// <param name='certificatePolicy'>The management policy for the certificate.</param> /// <param name="certificateAttributes">The attributes of the certificate (optional)</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The updated certificate.</returns> public static async Task <CertificateBundle> UpdateCertificateAsync(this IKeyVaultClient operations, string certificateIdentifier, CertificatePolicy certificatePolicy = default(CertificatePolicy), CertificateAttributes certificateAttributes = null, IDictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(certificateIdentifier)) { throw new ArgumentNullException(nameof(certificateIdentifier)); } var certId = new CertificateIdentifier(certificateIdentifier); using (var _result = await operations.UpdateCertificateWithHttpMessagesAsync(certId.Vault, certId.Name, certId.Version ?? string.Empty, certificatePolicy, certificateAttributes, tags, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Gets a certificate. /// </summary> /// <param name="certificateIdentifier">The URL for the certificate.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>The retrieved certificate</returns> public static async Task <CertificateBundle> GetCertificateAsync(this IKeyVaultClient operations, string certificateIdentifier, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(certificateIdentifier)) { throw new ArgumentNullException(nameof(certificateIdentifier)); } var certId = new CertificateIdentifier(certificateIdentifier); using (var _result = await operations.GetCertificateWithHttpMessagesAsync(certId.Vault, certId.Name, certId.Version ?? string.Empty, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Purges the deleted certificate with immediate effect. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted certificate, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>Task representing the asynchronous execution of this request.</returns> public static async Task PurgeDeletedCertificateAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) { throw new ArgumentNullException(nameof(recoveryId)); } var certificateRecoveryId = new DeletedCertificateIdentifier(recoveryId); using (var _result = await operations.PurgeDeletedCertificateWithHttpMessagesAsync(certificateRecoveryId.Vault, certificateRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return; } }
/// <summary> /// Recovers the deleted key. /// </summary> /// <param name="recoveryId">The recoveryId of the deleted key, returned from deletion.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the recovered key</returns> public static async Task <KeyBundle> RecoverDeletedKeyAsync(this IKeyVaultClient operations, string recoveryId, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(recoveryId)) { throw new ArgumentNullException(nameof(recoveryId)); } var keyRecoveryId = new DeletedKeyIdentifier(recoveryId); using (var _result = await operations.RecoverDeletedKeyWithHttpMessagesAsync(keyRecoveryId.Vault, keyRecoveryId.Name, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Updates the attributes associated with the specified secret /// </summary> /// <param name="secretIdentifier">The URL of the secret</param> /// <param name="contentType">Type of the secret value such as password.</param> /// <param name="tags">Application-specific metadata in the form of key-value pairs</param> /// <param name="secretAttributes">Attributes for the secret. For more information on possible attributes, see SecretAttributes.</param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns>A response message containing the updated secret</returns> public static async Task <SecretBundle> UpdateSecretAsync(this IKeyVaultClient operations, string secretIdentifier, string contentType = null, SecretAttributes secretAttributes = null, Dictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(secretIdentifier)) { throw new ArgumentNullException(nameof(secretIdentifier)); } var secretId = new SecretIdentifier(secretIdentifier); using (var _result = await operations.UpdateSecretWithHttpMessagesAsync(secretId.Vault, secretId.Name, secretId.Version, contentType, secretAttributes, tags, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }