コード例 #1
0
        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");
            }
        }
コード例 #2
0
        // 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);
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        public static IConfiguration SetEnvironmentVariablesFromConfiguration(this IConfiguration config)
        {
            var dict = config.AsEnumerable().ToDictionary(x => x.Key, x => x.Value);

            KeyVaultProvider.SetEnvironmentVariables(dict);
            return(config);
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        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);
        }
コード例 #8
0
        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));
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        /// <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()))));
        }
コード例 #11
0
        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()))));
        }
コード例 #12
0
        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));
        }
コード例 #13
0
        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);
        }
コード例 #14
0
        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);
        }
コード例 #15
0
        /// <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));
        }
コード例 #16
0
        /// <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()))));
        }
コード例 #17
0
ファイル: GetSecretTests.cs プロジェクト: patrickCode/Azure
        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);
        }
コード例 #18
0
        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;
            }
        }
コード例 #19
0
        /// <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);
        }