/// <summary>
        /// This method creates a Polly retry policy when there is cosmos exception with code Unauthorized.
        /// </summary>
        /// <returns>The AsyncRetryPolicy</returns>
        private AsyncRetryPolicy GetCosmosRetryPolicy()
        {
            return(Policy.Handle <CosmosException>(e => e.StatusCode == HttpStatusCode.Unauthorized)
                   .RetryAsync(Constants.RetryCount, async(exception, retryCount) =>
            {
                try
                {
                    await SemaphoreSlim.WaitAsync().ConfigureAwait(false);
                    logger.LogInformation("Read the cosmos key from KeyVault.");

                    // Get the latest cosmos key.
                    Microsoft.Azure.KeyVault.Models.SecretBundle cosmosKeySecret = await keyVaultConnection.Client.GetSecretAsync(keyVaultConnection.Address, Constants.CosmosKey).ConfigureAwait(false);

                    CosmosConfig config = new CosmosConfig();

                    CosmosClientOptions options = new CosmosClientOptions
                    {
                        RequestTimeout = TimeSpan.FromSeconds(config.Timeout),
                        MaxRetryAttemptsOnRateLimitedRequests = config.Retries,
                        MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(config.Timeout),
                    };

                    services.AddSingleton <CosmosClient>(new CosmosClient(configuration[Constants.CosmosUrl], cosmosKeySecret.Value));

                    logger.LogInformation("Refresh cosmos connection with upadated secret.");
                    await dal.Reconnect(new Uri(configuration[Constants.CosmosUrl]), cosmosKeySecret.Value, configuration[Constants.CosmosDatabase], configuration[Constants.CosmosCollection], services.BuildServiceProvider().GetService <CosmosClient>()).ConfigureAwait(false);
                }
                finally
                {
                    // release the semaphore
                    SemaphoreSlim.Release();
                }
            }));
        }
示例#2
0
        /// <summary>
        /// Retrieves the certificate from Azure KeyVault
        /// </summary>
        /// <returns></returns>
        private X509Certificate2 GetKeySigningCertificate()
        {
            AzureServiceTokenProvider azTokenProvider = new AzureServiceTokenProvider();
            KeyVaultClient            kvClient        = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azTokenProvider.KeyVaultTokenCallback));

            Microsoft.Azure.KeyVault.Models.SecretBundle secret = kvClient.GetSecretAsync("https://sincer-keyvault.vault.azure.net", "sincer-auth-cert")
                                                                  .GetAwaiter().GetResult();
            byte[] secretValue = Convert.FromBase64String(secret.Value);
            return(new X509Certificate2(secretValue, null as string, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable));
        }
示例#3
0
        /// <summary>
        /// Gets the stored key vault configuration.
        /// </summary>
        /// <param name="configuration">IConfiguration.</param>
        /// <param name="deliveryChannelSecretUrl">Azure Key Vault URL where the delivery channel's configuration is stored.</param>
        /// <returns>Delivery channel secret.</returns>
        public static async Task <string> GetDeliveryChannelSecretAsync(IConfiguration configuration, string deliveryChannelSecretUrl)
        {
            string?azureConnectionString     = configuration.GetValue <string>("AzureServicesAuthConnectionString");
            var    azureServiceTokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider(azureConnectionString);

            using var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            Microsoft.Azure.KeyVault.Models.SecretBundle accountKey = await keyVaultClient.GetSecretAsync(deliveryChannelSecretUrl).ConfigureAwait(false);

            return(accountKey.Value);
        }
示例#4
0
        private string GetSecret(IServiceCollection services)
        {
            KeyVaultOptions keyVaultOptions = new KeyVaultOptions();

            Configuration.Bind("KeyVaultOptions", keyVaultOptions);
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            Microsoft.Azure.KeyVault.Models.SecretBundle secret = keyVaultClient.GetSecretAsync(keyVaultOptions.AzurePlaygroundOAuthSecretUrl).Result;
            return(secret.Value);
        }
        public static async Task <string> GetConnectionString()
        {
            string uriStr = System.Environment.GetEnvironmentVariable("ConnectionSecretUri");
            var    azureServiceTokenProvider = new AzureServiceTokenProvider();

            var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            Microsoft.Azure.KeyVault.Models.SecretBundle secret = await kv.GetSecretAsync(uriStr);

            return(secret.Value);
        }
示例#6
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(EncryptionHelper.GetToken));

            Task <Microsoft.Azure.KeyVault.Models.SecretBundle> task = kv.GetSecretAsync(WebConfigurationManager.AppSettings["SecretUri"]);

            task.ContinueWith(continuation =>
            {
                Microsoft.Azure.KeyVault.Models.SecretBundle secretBundle = continuation.Result;
                EncryptionHelper.EncryptSecret = secretBundle.Value;
            });
        }
        public static async System.Threading.Tasks.Task RunAsync([BlobTrigger("uploads/{name}", Connection = "storageAcct")] Stream myBlob, string name, ILogger log)
        {
            // Sample Logging
            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");

            // Grab Secrets and Keys from Azure KeyVault
            // Reference: https://medium.com/statuscode/getting-key-vault-secrets-in-azure-functions-37620fd20a0b
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback), kvhttpClient);

            Microsoft.Azure.KeyVault.Models.SecretBundle secretBundle = await kvClient.GetSecretAsync(Environment.GetEnvironmentVariable("sftpkey"));

            // Convert key to stream data type for PrivateKeyFile variable
            byte[]       byteArray = Encoding.ASCII.GetBytes(secretBundle.Value);
            MemoryStream sshkey    = new MemoryStream(byteArray);

            // Using SSH.Net Library: https://github.com/sshnet/SSH.NET ; Other ssh/sftp libs can be found here: https://www.sftp.net/client-libraries
            // Sample code for SSH.NET: https://ourcodeworld.com/articles/read/369/how-to-access-a-sftp-server-using-ssh-net-sync-and-async-with-c-in-winforms
            PrivateKeyFile keyFile  = new PrivateKeyFile(sshkey);
            var            keyFiles = new[] { keyFile };

            // These variables can also be stored on key vault instead of local.settings.json. If it is stored in keyvault, you will need to change the ref. to that of the location of the keys.
            string host         = Environment.GetEnvironmentVariable("serveraddress");
            string sftpUsername = Environment.GetEnvironmentVariable("sftpusername");
            string password     = Environment.GetEnvironmentVariable("password");

            var methods = new List <AuthenticationMethod>();

            methods.Add(new PasswordAuthenticationMethod(sftpUsername, password));
            methods.Add(new PrivateKeyAuthenticationMethod(sftpUsername, keyFiles));

            // Connect to SFTP Server and Upload file
            ConnectionInfo con = new ConnectionInfo(host, 22, sftpUsername, methods.ToArray());

            using (var client = new SftpClient(con))
            {
                client.Connect();
                client.UploadFile(myBlob, $"/uploads/{name}");

                var files = client.ListDirectory("/uploads");
                foreach (var file in files)
                {
                    log.LogInformation(file.Name);
                }
                client.Disconnect();
            }
        }
示例#8
0
        public async Task <string> GetSecretValue(string keyVaultAddress, string secretName)
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();

            using (var keyVaultClient = new KeyVaultClient(
                       new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)))
            {
                Microsoft.Azure.KeyVault.Models.SecretBundle secret = null;
                try
                {
                    secret = await keyVaultClient.GetSecretAsync(keyVaultAddress, secretName)
                             .ConfigureAwait(false);

                    return(secret.Value);
                }
                catch (Exception e)
                {
                    Logger.Error($"Error: fail to get secret '{secretName}' for {e}");
                }
                return(null);
            }
        }
示例#9
0
        /// <summary>
        /// This method creates a Polly retry policy when there is cosmos exception with code Unauthorized.
        /// </summary>
        /// <returns>The AsyncRetryPolicy</returns>
        private AsyncRetryPolicy GetCosmosRetryPolicy()
        {
            return(Policy.Handle <CosmosException>(e => e.StatusCode == HttpStatusCode.Unauthorized)
                   .RetryAsync(Constants.RetryCount, async(exception, retryCount) =>
            {
                try
                {
                    await SemaphoreSlim.WaitAsync().ConfigureAwait(false);
                    logger.LogInformation("Read the cosmos key from KeyVault.");

                    // Get the latest cosmos key.
                    Microsoft.Azure.KeyVault.Models.SecretBundle cosmosKeySecret = await keyVaultConnection.Client.GetSecretAsync(keyVaultConnection.Address, Constants.CosmosKey).ConfigureAwait(false);

                    logger.LogInformation("Refresh cosmos connection with upadated secret.");
                    await dal.Reconnect(new Uri(configuration[Constants.CosmosUrl]), cosmosKeySecret.Value, configuration[Constants.CosmosDatabase], configuration[Constants.CosmosCollection]).ConfigureAwait(false);
                }
                finally
                {
                    // release the semaphore
                    SemaphoreSlim.Release();
                }
            }));
        }
 public virtual string GetKey(Microsoft.Azure.KeyVault.Models.SecretBundle secret)
 {
     throw null;
 }