private async Task <byte[]> GetCertificateData(KeyVaultClient client, KeyVaultCertificateAttribute input) { if (input.FetchPrivateKey) { var certificateSecret = string.IsNullOrWhiteSpace(input.CertificateVersion) ? await client.GetSecretAsync( vaultBaseUrl : KeyVaultHelpers.GetVaultBaseUrl(input.VaultName), secretName : input.CertificateName) : await client.GetSecretAsync( vaultBaseUrl : KeyVaultHelpers.GetVaultBaseUrl(input.VaultName), secretName : input.CertificateName, secretVersion : input.CertificateVersion); return(Convert.FromBase64String(certificateSecret.Value)); } else { var certificateObject = string.IsNullOrWhiteSpace(input.CertificateVersion) ? await client.GetCertificateAsync( vaultBaseUrl : KeyVaultHelpers.GetVaultBaseUrl(input.VaultName), certificateName : input.CertificateName) : await client.GetCertificateAsync( vaultBaseUrl : KeyVaultHelpers.GetVaultBaseUrl(input.VaultName), certificateName : input.CertificateName, certificateVersion : input.CertificateVersion); return(certificateObject.Cer); } }
public async Task IcmClientTestAsync() { Debugger.Launch(); var appKey = GetApplicationKey().ShouldBeSuccess(); var config = new App.Monitor.Configuration { AzureAppKey = appKey.Value ! }; var clock = new MemoryClock(); clock.Increment(); var keyVault = new KeyVaultClient( config.KeyVaultUrl, config.AzureTenantId, config.AzureAppId, config.AzureAppKey, clock, cacheTimeToLive: TimeSpan.FromSeconds(1)); keyVault.IcmCallsCounter.Value.Should().Be(0); // Simulate that the certificate has been acquired before. _ = await keyVault.GetCertificateAsync(config.IcmCertificateName); keyVault.IcmCallsCounter.Value.Should().Be(1); var icmClient = new IcmClient(keyVault, config.IcmUrl, config.IcmConnectorId, config.IcmCertificateName, clock); var incident = new IcmIncident( stamp: "Test", environment: "PROD", machines: new [] { "MachineA", "MachineB" }, correlationIds: new[] { "GuidA", "GuidB" }, severity: 4, description: "This incident was created for testing the cache monitor", title: "Cache Monitor Test Incident", incidentTime: DateTime.Now, cacheTimeToLive: null); await icmClient.EmitIncidentAsync(incident); // Should have used cached cert. keyVault.IcmCallsCounter.Value.Should().Be(1); // Simulate that the certificate will be acquired in the future. clock.AddSeconds(2); _ = await keyVault.GetCertificateAsync(config.IcmCertificateName); keyVault.IcmCallsCounter.Value.Should().Be(2); } }
/// <inheritdoc /> public async Task <byte[]> GetCertificateAsync(string certificateName) { using KeyVaultClient client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(_azureServiceTokenProvider.KeyVaultTokenCallback)); CertificateBundle cert = await client.GetCertificateAsync(_vaultUri, certificateName); return(cert.Cer); }
static void Main(string[] args) { try{ //run through the arguments and break them into variables. ProcessArgs(args); //if user is requesting validaiton of a file, only run verifydoc and exit. if (ValidateFile != null) { VerifyDoc(); } else { //create KeyVault Client and authenticate with AAD. (GetAccessToken method.) keyVault = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(GetAccessToken), new HttpClient()); //get cert bundle from supplied certificate name. publicCertBundle = keyVault.GetCertificateAsync(KeyVaultAddress, CertName).Result; //get secret (private key) bundle from information in public cert bundle pointing to current key and version associated to cert. secretKeyBundle = keyVault.GetKeyAsync(publicCertBundle.KeyIdentifier.Vault, publicCertBundle.KeyIdentifier.Name).Result; //sign the doc yo! SignDoc(); } } catch (Exception e) { Console.Write("\n\n Error Caught: \n\n" + e.Message); } }
public async Task <ErrorOr <AzureKeyVaultMaterializedConfiguration> > Materialize(AzureKeyVaultSignConfigurationSet configuration) { async Task <string> Authenticate(string authority, string resource, string scope) { if (!string.IsNullOrWhiteSpace(configuration.AzureAccessToken)) { return(configuration.AzureAccessToken); } var context = new AuthenticationContext(authority); ClientCredential credential = new ClientCredential(configuration.AzureClientId, configuration.AzureClientSecret); try { var result = await context.AcquireTokenAsync(resource, credential); return(result.AccessToken); } catch (AdalServiceException e) when(e.StatusCode >= 400 && e.StatusCode < 500) { return(null); } } var vault = new KeyVaultClient(Authenticate); var azureCertificate = await vault.GetCertificateAsync(configuration.AzureKeyVaultUrl, configuration.AzureKeyVaultCertificateName); var certificate = new X509Certificate2(azureCertificate.Cer); var keyId = azureCertificate.KeyIdentifier; return(new AzureKeyVaultMaterializedConfiguration(vault, certificate, keyId)); }
static async Task Main(string[] args) { KeyVaultClient client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(AuthenticationCallback)); // Compute digest of data byte[] dataToSign = Encoding.ASCII.GetBytes("Hello world!"); byte[] hash = HashAlgorithm.Create(_hashAlg.Name).ComputeHash(dataToSign); // Construct DER encoded PKCS#1 DigestInfo structure defined in RFC 8017 byte[] pkcs1DigestInfo = CreatePkcs1DigestInfo(hash, _hashAlg); // Sign digest with private key var keyOperationResult = await client.SignAsync(_keyId, "RSNULL", pkcs1DigestInfo).ConfigureAwait(false); byte[] signature = keyOperationResult.Result; // Get public key from certificate var certBundle = await client.GetCertificateAsync(_certId).ConfigureAwait(false); X509Certificate2 cert = new X509Certificate2(certBundle.Cer); RSA rsaPubKey = cert.GetRSAPublicKey(); // Verify digest signature with public key if (!rsaPubKey.VerifyHash(hash, signature, _hashAlg, RSASignaturePadding.Pkcs1)) { throw new Exception("Invalid signature"); } }
public async Task <TOutput> InvokeAsync <TInput, TOutput>(TInput input, FunctionOptionBase options) { var keyOptions = options as KeyVaultFunctionOptions; keyvault_client = keyOptions.ClientId; keyvault_secret = keyOptions.ClientSecret; keyvault_url = keyOptions.Url; KVClient = new KeyVaultClient(GetToken, keyOptions.Client); string elementName = input as string; TOutput result; if (typeof(TOutput) == typeof(SecretBundle)) { if (Log != null) { Log.LogDebug("Using GetSecretAsync"); } result = (TOutput)(object)(await KVClient.GetSecretAsync(keyvault_url, elementName)); } else { //if(typeof(TOutput)==typeof(CertificateBundle)) if (Log != null) { Log.LogDebug("Using GetCertificateAsync"); } result = (TOutput)(object)await KVClient.GetCertificateAsync(keyvault_url, elementName); } return(result); }
public static async Task <X509Certificate2> DownloadCertificateWithPrivateKey(IConfiguration config, ILogger logger, string certificateName) { try { using (var kvClient = new KeyVaultClient(GetToken)) { var kvCertificate = await kvClient.GetCertificateAsync($"{Url(config).NoEndingSlash()}/certificates/{certificateName}"); var kvCertificateSecret = await kvClient.GetSecretAsync(kvCertificate.SecretIdentifier.BaseIdentifier); var publicAndPrivateKey = Convert.FromBase64String(kvCertificateSecret.Value); var certificate = new X509Certificate2(publicAndPrivateKey, (string)null, X509KeyStorageFlags.MachineKeySet); return(certificate); } } catch (Exception e) { logger.LogCritical("Cannot download cert from KeyVault.", e); throw; } async Task <string> GetToken(string authority, string resource, string scope) { var authContext = new AuthenticationContext(authority); var clientCred = new ClientCredential(ClientId(config), ClientSecret(config)); var result = await authContext.AcquireTokenAsync(resource, clientCred); return(result.AccessToken); } }
private async void getCert() { var certid = "https://mahoekstkeyvault.vault.azure.net/certificates/mahoekstsigningcert/433f9ac74bef4213817105287d954ba1"; var provider = new AzureServiceTokenProvider(); var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback)); var keyvaultpubliccert = await kv.GetCertificateAsync(certid); //we schould cache this cert for x hours }
public static async Task <AzureKeyVaultMaterializedConfiguration> Materialize(AzureKeyVaultSignConfigurationSet configuration) { async Task <string> Authenticate(string authority, string resource, string scope) { if (!string.IsNullOrWhiteSpace(configuration.AzureAccessToken)) { return(configuration.AzureAccessToken); } var context = new AuthenticationContext(authority); ClientCredential credential = new ClientCredential(configuration.AzureClientId, configuration.AzureClientSecret); AuthenticationResult result = await context.AcquireTokenAsync(resource, credential); if (result == null) { throw new InvalidOperationException("Authentication to Azure failed."); } return(result.AccessToken); } var client = new HttpClient(); var vault = new KeyVaultClient(Authenticate, client); var azureCertificate = await vault.GetCertificateAsync(configuration.AzureKeyVaultUrl, configuration.AzureKeyVaultCertificateName); var x509Certificate = new X509Certificate2(azureCertificate.Cer); var keyId = azureCertificate.KeyIdentifier; var key = await vault.GetKeyAsync(keyId.Identifier); return(new AzureKeyVaultMaterializedConfiguration(vault, x509Certificate, key, configuration.FileDigestAlgorithm, configuration.PkcsDigestAlgorithm)); }
// NOTE - this would be the preferred way to create the certificate in Azure Key Vault, as the certificate's private key never leaves // the service. However, it does not currently support specifying that we want to create a CA certificate using the certificate basic constraints. // This code is left here for reference. // // ReSharper disable once UnusedMember.Local private async Task <X509Certificate2> CreateCertificateInKeyVaultAsync(KeyVaultClient client) { var certificateOperation = await client.CreateCertificateAsync( _vaultBaseUrl, _certificateName, new CertificatePolicy( keyProperties : new KeyProperties(false, "RSA", 2048, false), x509CertificateProperties : new X509CertificateProperties( "CN=" + RootSubjectName, keyUsage : new List <string> { X509KeyUsageFlags.KeyCertSign.ToString() }, ekus : new List <string> { "1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.1" }), issuerParameters : new IssuerParameters("Self"))); while (certificateOperation.Status == "inProgress") { Console.WriteLine($"Creation of certificate '{_certificateName}' is in progress"); await Task.Delay(1000); certificateOperation = await client.GetCertificateOperationAsync(_vaultBaseUrl, _certificateName); } Console.WriteLine($"Creation of certificate '{_certificateName}' is in status '{certificateOperation.Status}'"); var certificate = await client.GetCertificateAsync(_vaultBaseUrl, _certificateName); return(new X509Certificate2(certificate.Cer)); }
public async Task <IEnumerable <SecurityKey> > GetValidationKeysAsync() { if (_cache.TryGetValue("ValidationKeys", out List <SecurityKey> validationKeys)) { return(validationKeys); } validationKeys = new List <SecurityKey>(); var certificateVersions = await _keyVaultClient.GetCertificateVersionsAsync(_vault, _certificateName); foreach (var certificateItem in certificateVersions) { if (certificateItem.Attributes.Enabled.HasValue && certificateItem.Attributes.Enabled.Value) { var certificateVersionBundle = await _keyVaultClient.GetCertificateAsync(certificateItem.Identifier.Identifier); var certificateVersionSecurityKey = await GetSecurityKeyFromSecretAsync(_keyVaultClient, certificateVersionBundle.SecretIdentifier.Identifier).ConfigureAwait(false); validationKeys.Add(certificateVersionSecurityKey); } } var options = new MemoryCacheEntryOptions(); options.AbsoluteExpiration = DateTime.Now.AddDays(1); _cache.Set("ValidationKeys", validationKeys, options); return(validationKeys); }
public X509Certificate2 GetCertificate(string certificateName) { string keyVaultUri = sentinelApiConfig.KeyVaultUri; try { // Craft the certificate URI var secretUri = new UriBuilder { Host = keyVaultUri, Scheme = "https" }.Uri; var kv = new KeyVaultClient(authenticationCallbacks.GetToken); var certificateBundle = kv.GetCertificateAsync(secretUri.ToString(), certificateName).GetAwaiter().GetResult(); var certificateSecret = kv.GetSecretAsync(certificateBundle.SecretIdentifier.Identifier); byte[] certificateDecoded = Convert.FromBase64String(certificateSecret.Result.Value); return(new X509Certificate2(certificateDecoded, string.Empty)); } catch (Exception ex) { throw new ApplicationException($"Error getting certificate <{certificateName}> from the KeyVault", ex); } }
public async Task <byte[]> GetCertificatesAsync(string name) { var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken)); var sec = await kv.GetCertificateAsync(_vaultBaseUrl, name); return(sec.Cer); }
private async Task GetCertificateFromKeyVault() { try { string clientId = KeyVaultOptions.Value.ClientId; string clientSecret = KeyVaultOptions.Value.ClientSecret; string certificateUrl = KeyVaultOptions.Value.CertificateUrl; using KeyVaultClient keyVaultClient = new KeyVaultClient(async(authority, resource, scope) => { ClientCredential adCredential = new ClientCredential(clientId, clientSecret); AuthenticationContext authenticationContext = new AuthenticationContext(authority, null); return((await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken); }); SecretBundle keyVaultCertificatePfx = await keyVaultClient.GetSecretAsync(certificateUrl.Replace("/certificates/", "/secrets/", StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false); CertificateBundle keyVaultCertificateCer = await keyVaultClient.GetCertificateAsync(certificateUrl.Replace("/secrets/", "/certificates/", StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false); DecryptionCertificate = keyVaultCertificatePfx.Value; EncryptionCertificate = Convert.ToBase64String(keyVaultCertificateCer.Cer); EncryptionCertificateId = keyVaultCertificatePfx.SecretIdentifier.Version; } catch (Exception ex) { Console.WriteLine(ex); } }
public async Task <IList <CertificateBundle> > GetExpiringCertificates([ActivityTrigger] DateTime currentDateTime) { var certificates = await _keyVaultClient.GetAllCertificatesAsync(_options.VaultBaseUrl); var list = certificates.Where(x => x.Tags != null && x.Tags.TryGetValue("Issuer", out var issuer) && (issuer == OldIssuerName || issuer == IssuerName)) .Where(x => (x.Attributes.Expires.Value - currentDateTime).TotalDays < 30) .ToArray(); var bundles = new List <CertificateBundle>(); foreach (var item in list) { bundles.Add(await _keyVaultClient.GetCertificateAsync(item.Id)); } return(bundles); }
public async Task <string> GetSecretAsync(string name) { var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken)); var sec = await kv.GetSecretAsync(_vaultBaseUrl, name); var cert = await kv.GetCertificateAsync(_vaultBaseUrl, name); return(sec?.Value); }
public async Task <ErrorOr <AzureKeyVaultMaterializedConfiguration> > Materialize(AzureKeyVaultSignConfigurationSet configuration) { var authenticationFailure = false; async Task <string> Authenticate(string authority, string resource, string scope) { if (!string.IsNullOrWhiteSpace(configuration.AzureAccessToken)) { return(configuration.AzureAccessToken); } var context = new AuthenticationContext(authority); ClientCredential credential = new ClientCredential(configuration.AzureClientId, configuration.AzureClientSecret); try { _logger.LogTrace("Acquiring access token from client id"); var result = await context.AcquireTokenAsync(resource, credential); _logger.LogTrace("Acquired access token from client id"); return(result.AccessToken); } catch (AdalServiceException e) when(e.StatusCode >= 400 && e.StatusCode < 500) { authenticationFailure = true; _logger.LogError("Failed to authenticate to Azure Key Vault. Please check credentials."); return(null); } } var vault = new KeyVaultClient(Authenticate); X509Certificate2 certificate; CertificateBundle azureCertificate; try { _logger.LogTrace($"Retrieving certificate {configuration.AzureKeyVaultCertificateName}."); azureCertificate = await vault.GetCertificateAsync(configuration.AzureKeyVaultUrl, configuration.AzureKeyVaultCertificateName); _logger.LogTrace($"Retrieved certificate {configuration.AzureKeyVaultCertificateName}."); certificate = new X509Certificate2(azureCertificate.Cer); } catch (Exception e) { if (!authenticationFailure) { _logger.LogError($"Failed to retrieve certificate {configuration.AzureKeyVaultCertificateName} from Azure Key Vault. Please verify the name of the certificate and the permissions to the certificate."); } return(e); } var keyId = azureCertificate.KeyIdentifier; return(new AzureKeyVaultMaterializedConfiguration(vault, certificate, keyId)); }
public ActionResult Index() { var authTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(authTokenProvider.KeyVaultTokenCallback)); var secret = keyVaultClient.GetCertificateAsync("insert your secret identifier"); ViewBag.Secret = $"The secret password is: {secret.Value}"; return(View()); }
/// <summary> /// Extracts PFX from a certificate uploaded or generated from KeyVault. This does not support certs uploaded into KeyVault using secret. /// </summary> /// <param name="certificateName">Name of the certificate.</param> /// <param name="certificateSecretName">Secret name of the certificate. This is usually certificate name.</param> /// <param name="fullDirectoryPath">The full directory path to drop PFX at.</param> /// <param name="keyVaultClient">The key vault client.</param> /// <param name="keyVaultUrl">The key vault URL.</param> /// <returns>Exit code for the operation.</returns> private static async Task <ExitCode> KeyVaultCertHandlerAsync( string certificateSource, string certificateName, string certificateSecretName, string fullDirectoryPath, KeyVaultClient keyVaultClient, string keyVaultUrl) { if (keyVaultClient == null) { Logger.LogError(CallInfo.Site(), "KeyVaultClient was not initialized. Make sure required params for KeyVault connection were passed"); return(ExitCode.KeyVaultConfigurationIncomplete); } if (string.IsNullOrEmpty(keyVaultUrl)) { Logger.LogError(CallInfo.Site(), "Invalid KeyVault uri."); return(ExitCode.KeyVaultConfigurationIncomplete); } SecretBundle certificateSecret; try { if (string.Equals(certificateSource, "KeyVaultSecret", StringComparison.OrdinalIgnoreCase) || string.Equals(certificateSource, "KeyVault", StringComparison.OrdinalIgnoreCase)) { certificateSecret = await keyVaultClient.GetSecretAsync(keyVaultUrl, certificateSecretName).ConfigureAwait(false); } else if (string.Equals(certificateSource, "KeyVaultCertificate", StringComparison.OrdinalIgnoreCase)) { var cert = await keyVaultClient.GetCertificateAsync(keyVaultUrl, certificateSecretName).ConfigureAwait(false); certificateSecret = await keyVaultClient.GetSecretAsync(cert.SecretIdentifier.ToString()).ConfigureAwait(false); } else { Logger.LogError(CallInfo.Site(), $"Specified KeyVault source is not supported: {certificateSource}"); return(ExitCode.KeyVaultConfigurationIncomplete); } } catch (Exception ex) { Logger.LogError(CallInfo.Site(), ex, "Failed to get certificate with secret name '{0}' from key vault '{1}'", certificateSecretName, keyVaultUrl); return(ExitCode.KeyVaultOperationFailed); } // Only supporting managed certs for now. if (certificateSecret.Managed != true) { Logger.LogError(CallInfo.Site(), "Failed to decrypt certificate. Only managed certificates are supported. Download the unmanaged cert from secret and reupload it to certificates."); return(ExitCode.FailedToDecodeCertFromKeyVault); } return(SaveCertificatePrivateKeyToDisk(Convert.FromBase64String(certificateSecret.Value), certificateName, fullDirectoryPath)); }
public X509Certificate2 GetCertificateFromKeyVault(string vaultCertificateName) { var keyVaultClient = new KeyVaultClient(AuthenticationCallback); var certBundle = keyVaultClient.GetCertificateAsync(_vaultAddress, vaultCertificateName).Result; var certContent = keyVaultClient.GetSecretAsync(certBundle.SecretIdentifier.Identifier).Result; var certBytes = Convert.FromBase64String(certContent.Value); var cert = new X509Certificate2(certBytes); return(cert); }
private async Task <X509Certificate2> GetCertificateAsync(string identitifier, KeyVaultClient keyVaultClient) { var certificateVersionBundle = await keyVaultClient.GetCertificateAsync(identitifier); 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 async Task <X509Certificate2> GetCertificateAsync() { if (certificate == null) { var cert = await client.GetCertificateAsync(CertificateInfo.KeyVaultUrl, CertificateInfo.CertificateName).ConfigureAwait(false); certificate = new X509Certificate2(cert.Cer); keyIdentifier = cert.KeyIdentifier; } return(certificate); }
public async Task <X509Certificate2> GetCert(string keyvalutPath, string certName) { var cert = await _kv.GetCertificateAsync(keyvalutPath, certName).ConfigureAwait(false); var secretRetrieved = await _kv.GetSecretAsync(cert.SecretIdentifier.ToString()).ConfigureAwait(false); var pfxBytes = Convert.FromBase64String(secretRetrieved.Value); var certificate = new X509Certificate2(pfxBytes); return(certificate); }
public async Task <bool> SignAsync(string packagePath, string outputPath, string timestampUrl, HashAlgorithmName signatureHashAlgorithm, HashAlgorithmName timestampHashAlgorithm, SignatureType signatureType, bool overwrite, string keyVaultCertificateName, string keyVaultUrl, string keyVaultClientId, string keyVaultClientSecret, string keyVaultAccessToken) { string validatedToken = null; async Task <string> Authenticate(string authority, string resource, string scope) { if (!string.IsNullOrWhiteSpace(keyVaultAccessToken)) { validatedToken = keyVaultAccessToken; return(keyVaultAccessToken); } var context = new AuthenticationContext(authority); var credential = new ClientCredential(keyVaultClientId, keyVaultClientSecret); var result = await context.AcquireTokenAsync(resource, credential) .ConfigureAwait(false); if (result == null) { throw new InvalidOperationException("Authentication to Azure failed."); } validatedToken = result.AccessToken; return(result.AccessToken); } var client = new KeyVaultClient(Authenticate, new HttpClient()); // We call this here to verify it's a valid cert // It also implicitly validates the access token or credentials var kvcert = await client.GetCertificateAsync(keyVaultUrl, keyVaultCertificateName) .ConfigureAwait(false); var publicCertificate = new X509Certificate2(kvcert.Cer); var keyIdentifier = kvcert.KeyIdentifier; var rsa = client.ToRSA(keyIdentifier, publicCertificate); return(await SignAsync(packagePath, outputPath, timestampUrl, signatureHashAlgorithm, timestampHashAlgorithm, overwrite, publicCertificate, rsa)); }
private static void StoreRootCAFromKeyVault() { var certificate = keyVaultClient.GetCertificateAsync($"https://{keyVaultName}.vault.azure.net", certificateName).GetAwaiter().GetResult(); var x509Cert = new X509Certificate2(certificate.Cer); using (X509Store certStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser)) { certStore.Open(OpenFlags.ReadWrite); certStore.Add(x509Cert); certStore.Close(); } }
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, AuthenticationExtensionConfig config) { return(services .AddAuthentication(config.DefaultScheme) .AddJwtBearer(JwtBearerAuthenticationScheme, options => { options.Authority = config.Authority; options.RequireHttpsMetadata = config.Environment.IsNotLocalOrDocker(); options.Audience = config.Audience; options.IncludeErrorDetails = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateActor = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, RequireExpirationTime = true, RequireSignedTokens = true, ValidateIssuerSigningKey = config.Environment.IsNotLocalOrDocker(), ValidAudience = config.Audience, ValidIssuer = config.Authority, AuthenticationType = JwtBearerAuthenticationScheme }; options.Events = new JwtBearerEvents { OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments($"/{SignalRHubNameConstants.RivaHub}")) { context.Token = accessToken; } return Task.CompletedTask; } }; if (config.Environment.IsNotLocalOrDocker()) { var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(new AzureServiceTokenProvider().KeyVaultTokenCallback)); var certificateBundle = kv.GetCertificateAsync($"https://{config.KeyVaultName}.vault.azure.net/", config.SigningCredentialCertificateName).GetAwaiter().GetResult(); var certificate = new X509Certificate2(certificateBundle.Cer); options.TokenValidationParameters.IssuerSigningKey = new X509SecurityKey(certificate); } }) .Services); }
private X509Certificate2 GetTokenCertificate() { if (string.IsNullOrEmpty(keyVaultSettings.ClientId) || string.IsNullOrEmpty(keyVaultSettings.ClientSecret)) { return(new X509Certificate2(certSettings.CertificatePath, certSettings.CertificatePwd)); } KeyVaultClient client = KeyVaultSettings.GetClient(keyVaultSettings.ClientId, keyVaultSettings.ClientSecret); CertificateBundle certificate = client.GetCertificateAsync(keyVaultSettings.SecretUri, certSettings.CertificateName).GetAwaiter().GetResult(); SecretBundle secret = client.GetSecretAsync(certificate.SecretIdentifier.Identifier).GetAwaiter().GetResult(); byte[] pfxBytes = Convert.FromBase64String(secret.Value); return(new X509Certificate2(pfxBytes)); }
internal async Task <SecurityKeyInfo> GetSecurityKeyFromCertificateAsync(Microsoft.Azure.KeyVault.Models.CertificateItem certificateItem) { var certificateVersionBundle = await _keyVaultClient.GetCertificateAsync(certificateItem.Identifier.Identifier); var certificatePrivateKeySecretBundle = await _keyVaultClient.GetSecretAsync(certificateVersionBundle.SecretIdentifier.Identifier); var privateKeyBytes = Convert.FromBase64String(certificatePrivateKeySecretBundle.Value); var certificateWithPrivateKey = new X509Certificate2(privateKeyBytes, (string)null, X509KeyStorageFlags.MachineKeySet); var tp = new SecurityKeyInfo(); //certificateWithPrivateKey.SignatureAlgorithm tp.Key = new X509SecurityKey(certificateWithPrivateKey); tp.SigningAlgorithm = SecurityAlgorithms.RsaSha256; return(tp); }
public async Task <KeyVaultCertificate> GetCertificate(string certificateName, bool includeKey = true) { var certificateBundle = await Client.GetCertificateAsync(_baseUrl, certificateName); certificateBundle.Validate(); var keyVaultCertificate = new KeyVaultCertificate { Cer = certificateBundle.Cer, X509Thumbprint = certificateBundle.X509Thumbprint }; if (includeKey && certificateBundle.KeyIdentifier == null) { keyVaultCertificate.Key = await GetKeyVaultKey(certificateBundle.Kid, certificateBundle.Sid); } return(keyVaultCertificate); }