internal static void DownloadAppSettings() { var xml = XDocument.Load(SecretsProvider.WebconfigFile); var doc = xml.Element("configuration"); var appSettings = doc.Element("appSettings"); if (appSettings == null) { doc.Add(XElement.Parse("<appSettings></appSettings>")); appSettings = doc.Element("appSettings"); } appSettings.Elements().Remove(); var tasks = new List <Task <bool> >(); foreach (var key in ConfigurationManager.AppSettings.AllKeys) { tasks.Add(Task.Run(async() => await KeyVaultProvider.DeleteSecretAsync(key))); var secret = ConfigurationManager.AppSettings[key]; appSettings.Add(XElement.Parse($"<add key=\"{key}\" value=\"{secret}\" />")); } xml.Save(SecretsProvider.WebconfigFile); var results = Task.WhenAll(tasks).Result; if (results.Any(x => !x)) { throw new KeyMasterException("Key Master couldn't delete all secrets from azure"); } }
// We really need this code only locally, as the scripts are applied via SQL, so we pretty much us the local connection string? private static string ReadConnectionString() { var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var currentDir = Directory.GetCurrentDirectory(); var configRoot = new ConfigurationBuilder() .SetBasePath(currentDir) .AddJsonFile("appsettings.json", false, false) .AddJsonFile($"appsettings.{environment}.json", true) .Build(); var section = configRoot.GetSection(AppSettings.SectionKey); var settings = new ServiceCollection() .Configure <AppSettings>(section) .AddSingleton(configRoot) .BuildServiceProvider() .GetService <IOptions <AppSettings> >(); var keyVaultPath = settings.Value.ConnectionStringKeyVaultPath; var readResult = KeyVaultProvider.TryProvidingSecret(keyVaultPath); if (!readResult.IsSuccess) { // This means we're on the build server, which actually doesn't need the connection string var tra = Environment.GetEnvironmentVariable("HelloWorld"); Console.WriteLine(tra); Debug.WriteLine(tra); return(tra); } return(readResult.Value); }
internal static void SendAppSettings() { var tasks = new List <Task <bool> >(); foreach (var key in ConfigurationManager.AppSettings.AllKeys) { tasks.Add(Task.Run(async() => await KeyVaultProvider.CreateOrUpdateAppSettingAsync(key, ConfigurationManager.AppSettings[key]))); } var results = Task.WhenAll(tasks).Result; if (results.Any(x => !x)) { throw new KeyMasterException("Key master couldn't send app secrets to azure"); } var xml = XDocument.Load(SecretsProvider.WebconfigFile); var doc = xml.Element("configuration"); var appSettings = doc.Element("appSettings"); if (appSettings != null) { appSettings.Remove(); } xml.Save(SecretsProvider.WebconfigFile); }
public async Task Should_retrieve_secret_using_MSI() { var provider = new KeyVaultProvider("https://keyvaultplugin.vault.azure.net/secrets/storage-connection-string/39fa2e560eaf4b8eab7bf0e1a33d2357"); var connectionString = await provider.GetConnectionString(); Assert.Equal("UseDevelopmentStorage=true", connectionString); }
public static IConfiguration SetEnvironmentVariablesFromConfiguration(this IConfiguration config) { var dict = config.AsEnumerable().ToDictionary(x => x.Key, x => x.Value); KeyVaultProvider.SetEnvironmentVariables(dict); return(config); }
public static IConfigurationBuilder AddAzureKeyVault(this IConfigurationBuilder configBuilder) { // We have to build the configuration first to get whether // or not we need to load KeyVault values explicitly. //var config = configBuilder.Build(); var keyVaultConfig = configBuilder.Build().GetConfiguration(); if (!keyVaultConfig.Enabled) { return(configBuilder); } if (string.IsNullOrWhiteSpace(keyVaultConfig.CertificateThumbprint)) { configBuilder.AddAzureKeyVault(keyVaultConfig.Uri, keyVaultConfig.ClientId , keyVaultConfig.ClientSecret); return(configBuilder); } // Preference for authentication by certificate. X509Certificate2 cert = KeyVaultProvider.LoadCertificate(keyVaultConfig.CertificateThumbprint); configBuilder.AddAzureKeyVault(keyVaultConfig.Uri, keyVaultConfig.ClientId, cert); return(configBuilder); }
internal static bool CreateOrUpdateAppSetting(string key, string value, Secrets secrets) { var appsettings = new AppSettings { ClientId = secrets.ClientId, ClientSecret = secrets.ClientSecret, DirectoryId = secrets.DirectoryId, SecretName = secrets.SecretName, KeyVaultUrl = secrets.KeyVaultUrl }; return(KeyVaultProvider.CreateOrUpdateAppSettingAsync(key, value, appsettings).Result); }
internal static string GetConnectionString(Secrets secrets) { var appsettings = new AppSettings { ClientId = secrets.ClientId, ClientSecret = secrets.ClientSecret, DirectoryId = secrets.DirectoryId, SecretName = secrets.SecretName, KeyVaultUrl = secrets.KeyVaultUrl }; return(KeyVaultProvider.GetConnectionString(appsettings)); }
public DbContext Create() { var secretResult = KeyVaultProvider.TryProvidingSecret(_appSettings.Value.ConnectionStringKeyVaultPath); var options = new DbContextOptionsBuilder() .UseSqlServer(secretResult.Value) .ConfigureWarnings(f => f.Throw()) .Options; var result = new AppDbContext(options); return(result); }
/// <summary> /// Generates a token for Customer tenant using partner user refresh token /// The expiry time calculation explined below is not strong. /// please use stardard ADAL library to gain access token by refresh token, which provides strongly typed classes with proper expirty time calculation. /// </summary> /// <param name="partnerTenantId">partner tenant id</param> /// <param name="customerTenantId">customer tenant id</param> /// <returns> /// Access token and expiry time. /// </returns> public static async Task <Tuple <string, DateTimeOffset> > LoginToCustomerGraph(string partnerTenantId, string customerTenantId) { KeyVaultProvider provider = new KeyVaultProvider(); string refreshToken = await provider.GetSecretAsync(partnerTenantId); JObject token = await AuthorizationUtilities.GetAADTokenFromRefreshToken( $"{AADInstance}/{customerTenantId}", "https://graph.windows.net", CPVApplicationId, CPVApplicationSecret, refreshToken); return(new Tuple <string, DateTimeOffset>(token["access_token"].ToString(), DateTimeOffset.UtcNow + TimeSpan.FromTicks(long.Parse(token["expires_on"].ToString())))); }
public static async Task <Tuple <string, DateTimeOffset> > LoginToPartnerCenter(string tenantId) { KeyVaultProvider provider = new KeyVaultProvider(); string refreshToken = await provider.GetSecretAsync(tenantId); JObject token = await AuthorizationUtilities.GetAADTokenFromRefreshToken( $"{AADInstance}/{tenantId}", "https://api.partnercenter.microsoft.com", CPVApplicationId, CPVApplicationSecret, refreshToken); return(new Tuple <string, DateTimeOffset>(token["access_token"].ToString(), DateTimeOffset.UtcNow + TimeSpan.FromTicks(long.Parse(token["expires_on"].ToString())))); }
public static async Task <Tuple <string, DateTimeOffset> > LoginToPartnerCenter(string tenantId) { KeyVaultProvider provider = new KeyVaultProvider(); string refreshToken = await provider.GetSecretAsync(tenantId); AuthenticationResult token = await serviceClient.RefreshAccessTokenAsync( $"https://login.microsoftonline.com/{tenantId}/oauth2/token", "https://api.partnercenter.microsoft.com", refreshToken, CSPApplicationId, CSPApplicationSecret).ConfigureAwait(false); return(new Tuple <string, DateTimeOffset>(token.AccessToken, token.ExpiresOn)); }
public async Task Should_retrieve_secret_using_application_id_and_key_vault_secret() { var environmentVariable = Environment.GetEnvironmentVariable("AzureServicesAuthConnectionString", EnvironmentVariableTarget.Machine); //"RunAs=App;AppId=aabbccdd-1234-5678-90ab-ffeeddccbbaa;TenantId=aabbccdd-1234-5678-90ab-ffeeddccbbaa;AppKey=oiafQ#jafi0a9fu#kaofjas43ifj@jasdf09jlakjsd=" var elements = environmentVariable.Split(';'); var clientId = elements[1].Replace("AppId=", string.Empty); var clientSecret = elements[3].Replace("AppKey=", string.Empty); var provider = new KeyVaultProvider(clientId: clientId, clientSecret: clientSecret, secretIdentifier: "https://keyvaultplugin.vault.azure.net/secrets/storage-connection-string/39fa2e560eaf4b8eab7bf0e1a33d2357"); var connectionString = await provider.GetConnectionString(); Assert.Equal("UseDevelopmentStorage=true", connectionString); }
internal static bool DeleteAppSetting(Secrets secrets, string key) { var appsettings = new AppSettings { ClientId = secrets.ClientId, ClientSecret = secrets.ClientSecret, DirectoryId = secrets.DirectoryId, SecretName = secrets.SecretName, KeyVaultUrl = secrets.KeyVaultUrl }; return(KeyVaultProvider.DeleteSecretAsync(key, appsettings).Result); }
/// <summary> /// Generates a token for Customer tenant using partner user refresh token /// The expiry time calculation explined below is not strong. /// please use stardard ADAL library to gain access token by refresh token, which provides strongly typed classes with proper expirty time calculation. /// </summary> /// <param name="partnerTenantId">partner tenant id</param> /// <param name="customerTenantId">customer tenant id</param> /// <returns> /// Access token and expiry time. /// </returns> public static async Task <Tuple <string, DateTimeOffset> > LoginToCustomerGraph(string partnerTenantId, string customerTenantId) { KeyVaultProvider provider = new KeyVaultProvider(); string refreshToken = await provider.GetSecretAsync(partnerTenantId); AuthenticationResult token = await serviceClient.RefreshAccessTokenAsync( $"https://login.microsoftonline.com/{customerTenantId}/oauth2/token", "https://graph.windows.net", refreshToken, CSPApplicationId, CSPApplicationSecret).ConfigureAwait(false); return(new Tuple <string, DateTimeOffset>(token.AccessToken, token.ExpiresOn)); }
/// <summary> /// Generates a token for Partner tenant using partner user refresh token /// The expiry time calculation explined below is not strong. /// please use stardard ADAL library to gain access token by refresh token, which provides strongly typed classes with proper expirty time calculation. /// </summary> /// <param name="partnerTenantId">partner tenant id</param> /// <returns> /// Access token and expiry time. /// </returns> public static async Task <Tuple <string, DateTimeOffset> > LoginToGraph(string partnerTenantId) { KeyVaultProvider provider = new KeyVaultProvider(); string refreshToken = await provider.GetSecretAsync(partnerTenantId); Newtonsoft.Json.Linq.JObject token = await AuthorizationUtilities.GetAADTokenFromRefreshToken( "https://login.microsoftonline.com/" + partnerTenantId, "https://graph.microsoft.com", CSPApplicationId, CSPApplicationSecret, refreshToken); return(new Tuple <string, DateTimeOffset>(token["access_token"].ToString(), DateTimeOffset.UtcNow + TimeSpan.FromTicks(long.Parse(token["expires_on"].ToString())))); }
public async Task Secret_GetByCertificate() { //Arrange IKeyVaultSecretReaderAsync keyVaultProvider = new KeyVaultProvider(_vaultName, _azureAdClientId, _appCertificateThumbprint, _certificateStoreLocation, _certificateStoreName); var secretKey = "secret-storage-key"; var expectedSecret = ""; //Act var secret = await keyVaultProvider.GetSecretAsync(secretKey, false); //Assert Assert.IsNotNull(secret); Assert.IsNotNull(secret.Value); Assert.AreEqual(expectedSecret, secret.Value); }
public override void Initialize(string name, NameValueCollection config) { try { // this should be moved to another entry point hook, but this is the easiest way for now. AzureKeyVaultConfigurationProvider.Initialize(); var connectionString = KeyVaultProvider.GetConnectionString(); config.Add(ConnectionStringName, connectionString); base.Initialize(name, config); } catch (KeyMasterException ex) { var logger = LoggerSource.Instance.GetLogger("KeyMaster"); logger.Fatal("Unrecoverable Key Master error", ex); throw ex; } }
/// <summary> /// Recieve the AuthCode and exchange it for an access token and refresh token /// </summary> /// <param name="notificationMessage"></param> private static async Task HandleAuthorizationCodeReceivedNotification(AuthorizationCodeReceivedNotification notificationMessage) { string partnerTenantId = notificationMessage.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; // Acquire a token using AuthCode Newtonsoft.Json.Linq.JObject tokenResult = await AuthorizationUtilities.GetAADTokenFromAuthCode( $"{AadInstance}/{partnerTenantId}", "https://api.partnercenter.microsoft.com", CSPApplicationId, CSPApplicationSecret, notificationMessage.Code, notificationMessage.OwinContext.Request.Uri.ToString()); string refreshToken = tokenResult["refresh_token"].ToString(); // Store the refresh token using partner tenant id as the key. // Marketplace application will use the partner tenant id as a key to retrive the refresh token to get authenticated against the user. KeyVaultProvider provider = new KeyVaultProvider(); await provider.AddSecretAsync(partnerTenantId, refreshToken).ConfigureAwait(false); }