static async Task MainAsync(string[] args) { var keyClient = new KeyVaultClient((authority, resource, scope) => { var adCredential = new ClientCredential(applicationId, applicationSecret); var authenticationContext = new AuthenticationContext(authority, null); return authenticationContext.AcquireToken(resource, adCredential).AccessToken; }); // Get the key details var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784"; var key = await keyClient.GetKeyAsync(keyIdentifier); var publicKey = Convert.ToBase64String(key.Key.N); using (var rsa = new RSACryptoServiceProvider()) { var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E }; rsa.ImportParameters(p); var byteData = Encoding.Unicode.GetBytes(textToEncrypt); // Encrypt and Decrypt var encryptedText = rsa.Encrypt(byteData, true); var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText); var decryptedText = Encoding.Unicode.GetString(decryptedData.Result); // Sign and Verify var hasher = new SHA256CryptoServiceProvider(); var digest = hasher.ComputeHash(byteData); var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest); var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result); } }
public async Task<IEnumerable<JsonWebKey>> GetAsync() { if (_jwk == null) { var keyVaultClient = new KeyVaultClient(_authentication.KeyVaultClientAuthenticationCallback); var keyBundle = await keyVaultClient.GetKeyAsync(_options.KeyIdentifier).ConfigureAwait(false); _jwk = new JsonWebKey(keyBundle.Key.ToString()); } return new List<JsonWebKey> { _jwk }; }
/// <summary> /// Retrieves the public portion of a key plus its attributes. /// </summary> /// <param name="keyName"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <KeyBundle> GetKeyAsync( string keyName, CancellationToken cancellationToken = default ) { var keyBundle = await _keyVaultClient .GetKeyAsync( _keyVault.Properties.VaultUri, keyName, cancellationToken ); return(keyBundle); }
public async Task <IEnumerable <JsonWebKey> > GetAsync() { if (_jwk == null) { var keyVaultClient = new KeyVaultClient(_authentication.KeyVaultClientAuthenticationCallback); var keyBundle = await keyVaultClient.GetKeyAsync(_options.KeyIdentifier).ConfigureAwait(false); _jwk = new JsonWebKey(keyBundle.Key.ToString()); } return(new List <JsonWebKey> { _jwk }); }
public async Task <JsonWebKey> GetKeyAsync(string vaultName, string keyName) { try { _logger.LogInformation("GetKeyAsync from KeyVault"); var key = await keyVaultClient.GetKeyAsync($"https://{vaultName}.vault.azure.net/", keyName); _logger.LogInformation("GetKeyAsync operation completed"); return(key.Key); } catch (Exception ex) { throw new InvalidOperationException(ex.Message); } }
public async Task <JsonWebKey> GetKeyAsync(string keyName) { JsonWebKey key = new JsonWebKey(); key = _memoryCache.Get(keyName) as JsonWebKey; if (key == null) { key = (await KeyVaultClient.GetKeyAsync(_vaultAddress, keyName) .ConfigureAwait(false)) .Key; } return(key); }
protected override async Task <byte[]> GetPublicKeyAsync() { var keyBundle = await KeyVaultClient.GetKeyAsync(VaultUrl); var xLen = keyBundle.Key.X.Length; var yLen = keyBundle.Key.Y.Length; var publicKey = new byte[1 + xLen + yLen]; publicKey[0] = 0x04; var offset = 1; Buffer.BlockCopy(keyBundle.Key.X, 0, publicKey, offset, xLen); offset = offset + xLen; Buffer.BlockCopy(keyBundle.Key.Y, 0, publicKey, offset, yLen); return(publicKey); }
public async Task <KeyBundle> GetKeyFromVault(string keyId) { var keyIdentifier = _keyVaultPath + "keys/" + keyId + "/"; try { KeyBundle key = await _keyVaultClient.GetKeyAsync(keyIdentifier); return(key); } catch (Exception ex) { Debug.Write(ex.ToString()); } return(null); }
public async Task <List <KeyValuePair <string, byte[]> > > __GetKeysAsync() { List <Task <KeyBundle> > keyTasks = (await _client.GetKeysAsync(_keyVaultUrl)) .AsEnumerable() .Select(async keyItem => await _client.GetKeyAsync(keyItem.Identifier.Identifier)) .ToList(); await Task.WhenAll(keyTasks); List <KeyValuePair <string, byte[]> > keyValuePairs = keyTasks.Select(secret => secret.Result) .Select(key => new KeyValuePair <string, byte[]>(key.KeyIdentifier.Name, key.Key.N)) .ToList(); return(keyValuePairs); }
static void getMyKey(IConfiguration config, KeyVaultClient keyVault) { // To-Do Make sure keyURI is not null or other possible exceptions string myKeyURI = config.GetSection("myKey").Value; // Get key from Key Vault try { KeyBundle key = keyVault.GetKeyAsync(myKeyURI).GetAwaiter().GetResult(); // To-Do Actually use a key for something... Console.WriteLine(key.Key); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static async Task <string> Encrypt(string value) { AuthenticationCallback callback = async(authority, resource, scope) => { var appId = ""; var appSecret = ""; System.Console.WriteLine($"Authority {authority}"); System.Console.WriteLine($"resource {resource}"); System.Console.WriteLine($"scope {scope}"); var authContext = new AuthenticationContext(authority); var credential = new ClientCredential(appId, appSecret); var authResult = await authContext.AcquireTokenAsync(resource, credential); return(authResult.AccessToken); }; System.Console.WriteLine($"Setting up client"); var client = new KeyVaultClient(callback); var key = await client.GetKeyAsync("https://wickedvault.vault.azure.net", "masterKey"); using (var rsa = new RSACryptoServiceProvider()) { var parameters = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E }; rsa.ImportParameters(parameters); var byteData = Encoding.Unicode.GetBytes(value); var encryptedText = rsa.Encrypt(byteData, fOAEP: true); var encodedText = Convert.ToBase64String(encryptedText); System.Console.WriteLine($"rsa encrypted text {encryptedText}"); System.Console.WriteLine($"encoded text {encodedText}"); return(encodedText); } }
public async Task <ActionResult> EncryptAsync(string dataToEncrypt) { AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); // Demonstrate how to get a key KeyBundle key = await keyVaultClient.GetKeyAsync(keyVaultOptions.VaultBaseUrl, keyVaultOptions.KeyName); // Here you can use the (public) key to do encryption which is faster // Or encrypt on the Azure side using the EncryptAsync operation // Note that you can call the EncryptAsync operation directly without calling the GetKeyAsync method above KeyOperationResult keyOperationResult = await keyVaultClient.EncryptAsync(keyVaultOptions.VaultBaseUrl, key.KeyIdentifier.Name, key.KeyIdentifier.Version, JsonWebKeyEncryptionAlgorithm.RSAOAEP, Encoding.UTF8.GetBytes(dataToEncrypt)); ViewData["Encrypted"] = Convert.ToBase64String(keyOperationResult.Result); return(View("Index")); }
/// <summary> /// Retrieves the public portion of a key plus its attributes. /// </summary> /// <param name="keyName"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <KeyBundle> GetKeyAsync( string keyName, CancellationToken cancellationToken = default ) { if (string.IsNullOrEmpty(keyName)) { throw new ArgumentNullException(nameof(keyName)); } var keyBundle = await _keyVaultClient .GetKeyAsync( _keyVault.Properties.VaultUri, keyName, cancellationToken ); return(keyBundle); }
public static RsaSecurityKey GetSigningKey(string keyVaultEndpoint, string keyPath) { if (string.IsNullOrEmpty(keyVaultEndpoint)) { throw new InvalidOperationException(); } var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback( azureServiceTokenProvider.KeyVaultTokenCallback)); var key = keyVaultClient.GetKeyAsync(keyPath).GetAwaiter().GetResult(); if (key == null) { throw new InvalidOperationException( "An error occurred while retrieving the signing key from Azure Key Vault."); } return(new RsaSecurityKey(keyVaultClient.ToRSA(key))); }
public async Task <string> EncryptAsync(string value) { var bundle = await client.GetKeyAsync(keyId); var key = bundle.Key; using (var rsa = new RSACryptoServiceProvider()) { var parameters = new RSAParameters() { Modulus = key.N, Exponent = key.E }; rsa.ImportParameters(parameters); var byteData = Encoding.Unicode.GetBytes(value); var encryptedText = rsa.Encrypt(byteData, fOAEP: true); var encodedText = Convert.ToBase64String(encryptedText); return(encodedText); } }
public async Task <HttpResponseMessage> UnsubscribeAll( [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req, [DurableClient] IDurableEntityClient client) { var body = await req.Content.ReadAsStringAsync(); var unsubscribeRequest = JsonConvert.DeserializeObject <UnsubscribeRequest>(body); if (unsubscribeRequest is null) { return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Not a Valid Request")); } if (!string.IsNullOrEmpty(unsubscribeRequest.Signature)) { var sig = Base64UrlEncoder.DecodeBytes(unsubscribeRequest.Signature); var values = string.Concat(unsubscribeRequest.PersonId.ToString(), unsubscribeRequest.UseCase); using (var rsa = new RSACryptoServiceProvider()) { var key = (await _keyVaultClient.GetKeyAsync(Environment.GetEnvironmentVariable("SIGNING_KEY_ID"))).Key; var p = new RSAParameters() { Modulus = key.N, Exponent = key.E }; rsa.ImportParameters(p); var isVerified = rsa.VerifyHash(values.HashString(), "Sha256", sig); if (!isVerified) { return(req.CreateResponse(HttpStatusCode.Forbidden)); } } } var id = new EntityId(nameof(CommsTrackingEntity), unsubscribeRequest.PersonId.ToString()); await client.SignalEntityAsync(id, nameof(ICommsTrackingEntity.UnsubscribeAll)); //await _loggingService.LogUnsubscribe(unsubscribeRequest.PersonId.ToString(), unsubscribeRequest.UseCase); return(req.CreateResponse(HttpStatusCode.OK)); }
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).ConfigureAwait(false); if (result == null) { throw new InvalidOperationException("Authentication to Azure failed."); } return(result.AccessToken); } var client = new HttpClient(); var vault = new KeyVaultClient(Authenticate, client); if (configuration.Mode == KeyVaultMode.Certificate) { var azureCertificate = await vault.GetCertificateAsync(configuration.AzureKeyVaultUrl, configuration.AzureKeyVaultKeyName).ConfigureAwait(false); var x509Certificate = new X509Certificate2(azureCertificate.Cer); var keyId = azureCertificate.KeyIdentifier; return(new AzureKeyVaultMaterializedConfiguration(vault, keyId, publicCertificate: x509Certificate)); } else if (configuration.Mode == KeyVaultMode.Key) { var bundle = await vault.GetKeyAsync(configuration.AzureKeyVaultUrl, configuration.AzureKeyVaultKeyName).ConfigureAwait(false); return(new AzureKeyVaultMaterializedConfiguration(vault, bundle.KeyIdentifier, bundle.Key)); } throw new ArgumentOutOfRangeException(nameof(configuration)); }
/// <summary> /// Function to access secret value /// </summary> /// <param name="keyPath">Input parameters for accessing secret information/param> /// <returns>Secret information for output</returns> public async Task <KeyBundle> GetKey(string keyPath) { try { if (_secretValidator.IsValidSecretURI(keyPath)) { KeyBundle keyBundle = await _keyVaultClient.GetKeyAsync(keyPath); return(keyBundle); } else { throw new ArgumentException($"{keyPath} is invalid"); } } catch (Exception) { Console.WriteLine($"Error while getting secret for path {keyPath}"); throw; } }
public async Task <JsonWebKey> GetJwk(string keyVaultIdentifier) { AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider(); KeyVaultSecurityKey.AuthenticationCallback keyVaultAuthCallback = new KeyVaultSecurityKey.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback); KeyVaultClient client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(keyVaultAuthCallback), EdnaExternalHttpClient.Create()); KeyBundle keyBundle = await client.GetKeyAsync(keyVaultIdentifier); JsonWebKey jwk = new JsonWebKey(keyBundle.Key.ToString()); //Pruning to remove values for certian properties that are optional return(new JsonWebKey() { Kid = keyVaultIdentifier, Kty = JsonWebAlgorithmsKeyTypes.RSA, Alg = Microsoft.IdentityModel.Tokens.SecurityAlgorithms.RsaSha256, Use = Microsoft.IdentityModel.Tokens.JsonWebKeyUseNames.Sig, E = jwk.E, N = jwk.N }); }
public async Task RunAsync() { try { #if DEBUG #else var keyVaultKey = await KeyVault.GetKeyAsync(TekExportKeyVaultKeyUrl); SigInfo.VerificationKeyId = keyVaultKey.Key.Kid; SigInfo.VerificationKeyVersion = keyVaultKey.KeyIdentifier.Version; #endif var items = await TekRepository.GetNextAsync(); await CreateAsync(items); } catch (Exception ex) { Logger.LogError(ex, $"Error on {nameof(TemporaryExposureKeyService)}"); throw; } }
public async Task ReadKeyFromVault() { try { _logger.LogInformation($"Keyvault driven approach."); var kvUri = "https://devkvpmtengineshared.vault.azure.net/keys/encryption-key/dc190f1de6604bdab494f50d0ce98bb7"; _logger.LogInformation($"Read Key From KeyVault: {kvUri} "); var azureServiceTokenProvider = new AzureServiceTokenProvider(); var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); _logger.LogInformation($"Getting Key from Vault."); var keyResult = await kvClient.GetKeyAsync(kvUri); _logger.LogInformation($"Exponent: {Convert.ToBase64String(keyResult.Key.E)}"); _logger.LogInformation($"Modulus {Convert.ToBase64String(keyResult.Key.N)}"); var rsaParameter = keyResult.Key.ToRSAParameters(); var plainTextData = "Hello World"; _logger.LogInformation($"Encrypting data using RSA parameters."); var provider = new RSACryptoServiceProvider(); provider.ImportParameters(rsaParameter); var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData); var edata = provider.Encrypt(bytesPlainTextData, true); _logger.LogInformation($"Decrpyting....... {edata.Length}"); var decryptedData = await kvClient.DecryptAsync(kvUri, JsonWebKeyEncryptionAlgorithm.RSAOAEP, edata); var decryptedText = Encoding.Unicode.GetString(decryptedData.Result); _logger.LogInformation($"Decrpyted data:{decryptedText}"); _logger.LogInformation("Done!"); } catch (Exception ex) { _logger.LogInformation(ex.Message); } }
static async Task MainAsync(string[] args) { var keyClient = new KeyVaultClient((authority, resource, scope) => { var adCredential = new ClientCredential(applicationId, applicationSecret); var authenticationContext = new AuthenticationContext(authority, null); return(authenticationContext.AcquireToken(resource, adCredential).AccessToken); }); // Get the key details var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784"; var key = await keyClient.GetKeyAsync(keyIdentifier); var publicKey = Convert.ToBase64String(key.Key.N); using (var rsa = new RSACryptoServiceProvider()) { var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E }; rsa.ImportParameters(p); var byteData = Encoding.Unicode.GetBytes(textToEncrypt); // Encrypt and Decrypt var encryptedText = rsa.Encrypt(byteData, true); var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText); var decryptedText = Encoding.Unicode.GetString(decryptedData.Result); // Sign and Verify var hasher = new SHA256CryptoServiceProvider(); var digest = hasher.ComputeHash(byteData); var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest); var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result); } }
//Option 2 //static void Main(string[] args) //{ // Task t = MainAsync(args); // t.Wait(); //} static async Task MainAsync(string[] args) { var keyClient = new KeyVaultClient(async(authority, resource, scope) => { var adCredential = new ClientCredential(config["AzureActiveDirectory:ClientId"], config["AzureActiveDirectory:ClientSecret"]); var authenticationContext = new AuthenticationContext(authority, null); return((await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken); }); // Get the key details var keyIdentifier = "https://rahulkeyvault.vault.azure.net:443/keys/NewKey"; var key = await keyClient.GetKeyAsync(config["KeyVault:Url"]); var publicKey = Convert.ToBase64String(key.Key.N); using (var rsa = new RSACryptoServiceProvider()) { var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E }; rsa.ImportParameters(p); var byteData = Encoding.Unicode.GetBytes(args[0]); // Encrypt and Decrypt var encryptedText = rsa.Encrypt(byteData, true); var decryptedData = await keyClient.DecryptAsync(keyIdentifier, "RSA-OAEP", encryptedText); var decryptedText = Encoding.Unicode.GetString(decryptedData.Result); // Sign and Verify var hasher = new SHA256CryptoServiceProvider(); var digest = hasher.ComputeHash(byteData); var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest); var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result); } }
/// <summary> /// Retrieves the signing credential (override to load key from alternative locations) /// </summary> /// <returns>The signing credential</returns> protected virtual async Task <AzureKeyVaultSigningCredentials> GetSigningCredentialsAsync() { if (_keyVaultKeyExponent == null && _keyVaultKeyModulus == null) { var keyVaultClient = new KeyVaultClient(KeyVaultClientAuthenticationCallback); var keyBundle = await keyVaultClient.GetKeyAsync(_options.KeyIdentifier).ConfigureAwait(false); _keyVaultKeyExponent = keyBundle.Key.E; _keyVaultKeyModulus = keyBundle.Key.N; } var rsa = RSA.Create(); rsa.ImportParameters(new RSAParameters { Exponent = _keyVaultKeyExponent, Modulus = _keyVaultKeyModulus, }); var securityKey = new RsaSecurityKey(rsa); return(new AzureKeyVaultSigningCredentials(securityKey, SecurityAlgorithms.Sha256Digest)); }
private async Task <List <KeyBundle> > GetKeyBundleVersionsAsync(KeyVaultClient keyVaultClient) { List <KeyItem> keyItems = new List <KeyItem>(); var page = await keyVaultClient.GetKeyVersionsAsync(_options.KeyVaultUrl, _options.KeyIdentifier); keyItems.AddRange(page); while (!string.IsNullOrWhiteSpace(page.NextPageLink)) { page = await keyVaultClient.GetKeyVersionsNextAsync(page.NextPageLink); keyItems.AddRange(page); } var keyBundles = new List <KeyBundle>(); foreach (var keyItem in keyItems) { var keyBundle = await keyVaultClient.GetKeyAsync(keyItem.Identifier.Identifier); keyBundles.Add(keyBundle); } return(keyBundles); }
private static async Task<string> GetKeys(KeyVaultClient keyVaultClient) { var keyIdentifier = "keyIdentifier"; var textToEncrypt = "This is a test message"; var byteData = Encoding.Unicode.GetBytes(textToEncrypt); var hasher = new SHA256CryptoServiceProvider(); var digest = hasher.ComputeHash(byteData); var signedResult = await keyVaultClient.SignAsync( keyIdentifier, JsonWebKeySignatureAlgorithm.RS256, digest); var isVerified = await keyVaultClient.VerifyAsync(keyIdentifier, "RS256", digest, signedResult.Result); var keyResult = await keyVaultClient.GetKeyAsync(keyIdentifier); var jsonWebKey = keyResult.Key.ToString(); var key = JsonConvert.DeserializeObject<JsonWebKey>(jsonWebKey); var rsa = new RSACryptoServiceProvider(); var p = new RSAParameters() { Modulus = key.N, Exponent = key.E }; rsa.ImportParameters(p); isVerified = rsa.VerifyHash(digest, "Sha256", signedResult.Result); return null; }
public static JsonWebKeySet GetJwks() { KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback( (authority, resource, scope) => KeyVaultUtil.GetToken(authority, resource, scope))); var key = Task.Run(() => keyVaultClient.GetKeyAsync(SignKey())).ConfigureAwait(false).GetAwaiter().GetResult(); var e = Base64UrlEncoder.Encode(key.Key.E); var n = Base64UrlEncoder.Encode(key.Key.E); var jsonWebKey = new Microsoft.IdentityModel.Tokens.JsonWebKey() { Kid = KEY, Kty = "RSA", E = Base64UrlEncoder.Encode(key.Key.E), N = Base64UrlEncoder.Encode(key.Key.N), Alg = "RS256" }; JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(); jsonWebKeySet.Keys.Add(jsonWebKey); return(jsonWebKeySet); }
protected string GetKeyUri(string keyName) { var retrievedKey = KeyVaultClient.GetKeyAsync(VaultAddress, keyName).GetAwaiter().GetResult(); return(retrievedKey.Key.Kid); }
private static async Task <IDictionary <String, String> > ReadItem(string vaultAddress, KeyVaultClient keyVaultClient, String key) { var retrievedKey = await keyVaultClient.GetKeyAsync(vaultAddress, key); return(retrievedKey.Tags); }
public string GetKeyVaultKey(string key) { return(keyVaultClient.GetKeyAsync(vaultUrl, key).GetAwaiter().GetResult().KeyIdentifier.Identifier); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { if (HostingEnvironment.IsDevelopment()) { services.AddDataProtection() .SetDefaultKeyLifetime(LoginCookieLifetime * 2); } else { IConfigurationSection dpConfig = Configuration.GetSection("DataProtection"); string vaultUri = Configuration["KeyVaultUri"]; string keyVaultKeyIdentifierName = dpConfig["KeyIdentifier"]; var provider = new AzureServiceTokenProvider(); var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback)); KeyBundle key = kvClient.GetKeyAsync(vaultUri, keyVaultKeyIdentifierName).GetAwaiter().GetResult(); services.AddDataProtection() .PersistKeysToAzureBlobStorage(new Uri(dpConfig["KeyFileUri"])) .ProtectKeysWithAzureKeyVault(kvClient, key.KeyIdentifier.ToString()) .SetDefaultKeyLifetime(LoginCookieLifetime * 2) .SetApplicationName(typeof(Startup).FullName); } ConfigureApiServices(services); services.Configure <CookiePolicyOptions>( options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.Lax; options.HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always; if (HostingEnvironment.IsDevelopment()) { options.Secure = CookieSecurePolicy.SameAsRequest; } else { options.Secure = CookieSecurePolicy.Always; } }); services.AddBuildAssetRegistry( options => { options.UseSqlServer(Configuration.GetSection("BuildAssetRegistry")["ConnectionString"]); }); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddFluentValidation(options => options.RegisterValidatorsFromAssemblyContaining <Startup>()) .AddRazorPagesOptions( options => { options.Conventions.AuthorizeFolder("/", MsftAuthorizationPolicyName); options.Conventions.AllowAnonymousToPage("/Index"); options.Conventions.AllowAnonymousToPage("/Error"); options.Conventions.AllowAnonymousToPage("/SwaggerUi"); }) .AddGitHubWebHooks() .AddApiPagination() .AddCookieTempDataProvider( options => { // Cookie Policy will not send this cookie unless we mark it as Essential // The application will not function without this cookie. options.Cookie.IsEssential = true; }); services.AddSingleton <IConfiguration>(Configuration); ConfigureAuthServices(services); services.AddSingleton <BackgroundQueue>(); services.AddSingleton <IHostedService>(provider => provider.GetRequiredService <BackgroundQueue>()); services.AddServiceFabricService <IDependencyUpdater>("fabric:/MaestroApplication/DependencyUpdater"); services.AddGitHubTokenProvider(); services.Configure <GitHubClientOptions>(o => { o.ProductHeader = new Octokit.ProductHeaderValue("Maestro", Assembly.GetEntryAssembly() .GetCustomAttribute <AssemblyInformationalVersionAttribute>() ?.InformationalVersion); }); services.Configure <GitHubTokenProviderOptions>( (options, provider) => { IConfigurationSection section = Configuration.GetSection("GitHub"); section.Bind(options); }); services.AddAzureDevOpsTokenProvider(); services.Configure <AzureDevOpsTokenProviderOptions>( (options, provider) => { var config = provider.GetRequiredService <IConfiguration>(); var tokenMap = config.GetSection("AzureDevOps:Tokens").GetChildren(); foreach (IConfigurationSection token in tokenMap) { options.Tokens.Add(token.GetValue <string>("Account"), token.GetValue <string>("Token")); } }); services.AddKustoClientProvider( options => { IConfigurationSection section = Configuration.GetSection("Kusto"); section.Bind(options); }); services.AddSingleton <IRemoteFactory, DarcRemoteFactory>(); services.AddMergePolicies(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { if (HostingEnvironment.IsDevelopment()) { services.AddDataProtection(); } else { IConfigurationSection dpConfig = Configuration.GetSection("DataProtection"); string vaultUri = Configuration["KeyVaultUri"]; string keyVaultKeyIdentifierName = dpConfig["KeyIdentifier"]; KeyVaultClient kvClient = ServiceHostConfiguration.GetKeyVaultClient(HostingEnvironment); KeyBundle key = kvClient.GetKeyAsync(vaultUri, keyVaultKeyIdentifierName).GetAwaiter().GetResult(); services.AddDataProtection() .PersistKeysToAzureBlobStorage(new Uri(dpConfig["KeyFileUri"])) .ProtectKeysWithAzureKeyVault(kvClient, key.KeyIdentifier.ToString()); } ConfigureApiServices(services); services.Configure <CookiePolicyOptions>( options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext <BuildAssetRegistryContext>( options => { options.UseSqlServer(Configuration.GetSection("BuildAssetRegistry")["ConnectionString"]); }); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddFluentValidation(options => options.RegisterValidatorsFromAssemblyContaining <Startup>()) .AddRazorPagesOptions( options => { options.Conventions.AuthorizeFolder("/"); options.Conventions.AllowAnonymousToPage("/Index"); }) .AddGitHubWebHooks() .AddApiPagination() .AddCookieTempDataProvider( options => { // Cookie Policy will not send this cookie unless we mark it as Essential // The application will not function without this cookie. options.Cookie.IsEssential = true; }); services.AddSingleton <IConfiguration>(Configuration); ConfigureAuthServices(services); services.AddSingleton <BackgroundQueue>(); services.AddSingleton <IHostedService>(provider => provider.GetRequiredService <BackgroundQueue>()); services.AddServiceFabricService <IDependencyUpdater>("fabric:/MaestroApplication/DependencyUpdater"); services.AddGitHubTokenProvider(); services.Configure <GitHubTokenProviderOptions>( (options, provider) => { IConfigurationSection section = Configuration.GetSection("GitHub"); section.Bind(options); options.ApplicationName = "Maestro"; options.ApplicationVersion = Assembly.GetEntryAssembly() .GetCustomAttribute <AssemblyInformationalVersionAttribute>() ?.InformationalVersion; }); services.AddMergePolicies(); }
public override void ConfigureServices(IServiceCollection services) { if (HostingEnvironment.IsDevelopment()) { services.AddDataProtection() .SetDefaultKeyLifetime(LoginCookieLifetime * 2); } else { IConfigurationSection dpConfig = Configuration.GetSection("DataProtection"); string vaultUri = Configuration["KeyVaultUri"]; string keyVaultKeyIdentifierName = dpConfig["KeyIdentifier"]; var provider = new AzureServiceTokenProvider(); var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback)); KeyBundle key = kvClient.GetKeyAsync(vaultUri, keyVaultKeyIdentifierName).GetAwaiter().GetResult(); services.AddDataProtection() .PersistKeysToAzureBlobStorage(new Uri(dpConfig["KeyFileUri"])) .ProtectKeysWithAzureKeyVault(kvClient, key.KeyIdentifier.ToString()) .SetDefaultKeyLifetime(LoginCookieLifetime * 2) .SetApplicationName(typeof(Startup).FullName); } ConfigureApiServices(services); services.Configure <CookiePolicyOptions>( options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.Lax; options.HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always; if (HostingEnvironment.IsDevelopment()) { options.Secure = CookieSecurePolicy.SameAsRequest; } else { options.Secure = CookieSecurePolicy.Always; } }); services.AddBuildAssetRegistry( options => { options.UseSqlServer(Configuration.GetSection("BuildAssetRegistry")["ConnectionString"]); }); services.AddRazorPages(options => { options.Conventions.AuthorizeFolder("/", MsftAuthorizationPolicyName); options.Conventions.AllowAnonymousToPage("/Index"); options.Conventions.AllowAnonymousToPage("/Error"); options.Conventions.AllowAnonymousToPage("/SwaggerUi"); }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddFluentValidation(options => options.RegisterValidatorsFromAssemblyContaining <Startup>()) .AddGitHubWebHooks() .AddApiPagination() .AddCookieTempDataProvider( options => { // Cookie Policy will not send this cookie unless we mark it as Essential // The application will not function without this cookie. options.Cookie.IsEssential = true; }); services.AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.Converters.Add(new StringEnumConverter { NamingStrategy = new CamelCaseNamingStrategy() }); options.SerializerSettings.Converters.Add( new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ", DateTimeStyles = DateTimeStyles.AdjustToUniversal }); }); services.AddSingleton(Configuration); ConfigureAuthServices(services); services.AddSingleton <BackgroundQueue>(); services.AddSingleton <IBackgroundQueue>(provider => provider.GetRequiredService <BackgroundQueue>()); services.AddSingleton <IHostedService>(provider => provider.GetRequiredService <BackgroundQueue>()); services.AddServiceFabricService <IDependencyUpdater>("fabric:/MaestroApplication/DependencyUpdater"); services.AddGitHubTokenProvider(); services.Configure <GitHubClientOptions>(o => { o.ProductHeader = new Octokit.ProductHeaderValue("Maestro", Assembly.GetEntryAssembly() .GetCustomAttribute <AssemblyInformationalVersionAttribute>() ?.InformationalVersion); }); services.Configure <GitHubTokenProviderOptions>( (options, provider) => { IConfigurationSection section = Configuration.GetSection("GitHub"); section.Bind(options); }); services.AddAzureDevOpsTokenProvider(); services.Configure <AzureDevOpsTokenProviderOptions>( (options, provider) => { var config = provider.GetRequiredService <IConfiguration>(); var tokenMap = config.GetSection("AzureDevOps:Tokens").GetChildren(); foreach (IConfigurationSection token in tokenMap) { options.Tokens.Add(token.GetValue <string>("Account"), token.GetValue <string>("Token")); } }); services.AddKustoClientProvider( options => { IConfigurationSection section = Configuration.GetSection("Kusto"); section.Bind(options); }); // We do not use AddMemoryCache here. We use our own cache because we wish to // use a sized cache and some components, such as EFCore, do not implement their caching // in such a way that will work with sizing. services.AddSingleton <DarcRemoteMemoryCache>(); services.AddScoped <IRemoteFactory, DarcRemoteFactory>(); services.AddSingleton(typeof(IActorProxyFactory <>), typeof(ActorProxyFactory <>)); services.EnableLazy(); services.AddMergePolicies(); services.Configure <SwaggerOptions>(options => { options.SerializeAsV2 = false; options.RouteTemplate = "api/{documentName}/swagger.json"; options.PreSerializeFilters.Add( (doc, req) => { bool http = HostingEnvironment.IsDevelopment() && !ServiceFabricHelpers.RunningInServiceFabric(); doc.Servers = new List <OpenApiServer> { new OpenApiServer { Url = $"{(http ? "http" : "https")}://{req.Host.Value}/", }, }; req.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*"; }); }); services.AddSingleton <ISystemClock, SystemClock>(); }