public async Task <string> GetSecretAsApplicationUsingClientSecretAsync() { logger.LogInformation("----- Client Secret Async"); SecretClientOptions options = KeyVaultUtility.CreateSecretClientOptions(); TokenCredentialOptions tokenOptions = KeyVaultUtility.CreateTokenCredentialOptions(); var credential = new ClientSecretCredential( applicationConfiguration.TenantId, applicationConfiguration.ClientId, Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET"),//applicationConfiguration.ClientSecret tokenOptions); var keyVault = keyVaultConfiguration.Url; var client = new SecretClient(new Uri(keyVault), credential, options); KeyVaultSecret secret = null; try { secret = await client.GetSecretAsync(keyVaultConfiguration.SecretName); return(secret.Value); } catch (Exception ex) { logger.LogError(ex, "Failed to get secret as client secret"); throw; } }
/// <summary> /// /// </summary> /// <param name="secretNames"></param> /// <param name="replaceDashesWithColons"> /// Set to false if the secrets are to be used with environment variables and not consumed by IConfigurationBuilder. /// </param> /// <returns></returns> public async Task <Dictionary <string, string> > GetKeyVaultSecretsAsync( List <string> secretNames = null, bool replaceDashesWithColons = true) { TokenCredential tokenCredential; if (string.IsNullOrEmpty(_keyVaultConfig.CertificateThumbprint)) { // Can be set via VisualStudio under Options -> Azure Service Authentication. Environment.SetEnvironmentVariable("AZURE_TENANT_ID", _keyVaultConfig.TenantId); Environment.SetEnvironmentVariable("AZURE_CLIENT_ID", _keyVaultConfig.ClientId); Environment.SetEnvironmentVariable("AZURE_CLIENT_SECRET", _keyVaultConfig.ClientSecret); tokenCredential = new DefaultAzureCredential(); } else { tokenCredential = GetCertificateCredential(); } var options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; var client = new SecretClient(new Uri(_keyVaultConfig.Uri) , tokenCredential, options); var secrets = new Dictionary <string, string>(); if (secretNames == null || !secretNames.Any()) { var secretProps = client.GetPropertiesOfSecretsAsync(CancellationToken.None); await foreach (var secretProp in secretProps) { string secretName = replaceDashesWithColons ? secretProp.Name.Replace("--", ":") : secretProp.Name; KeyVaultSecret secret = await client.GetSecretAsync(secretProp.Name); secrets.Add(secretName, secret.Value); } return(secrets); } foreach (string name in secretNames) { string secretName = replaceDashesWithColons ? name.Replace("--", ":") : name; KeyVaultSecret secret = await client.GetSecretAsync(name); secrets.Add(secretName, secret.Value); } return(secrets); }
public ActionResult Index() { SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; var client = new SecretClient (new Uri("https://vault-demo01.vault.azure.net/"), new DefaultAzureCredential(), options); KeyVaultSecret secret = client.GetSecret("password"); string secretValue = secret.Value; ViewData["secretValue"] = secretValue; ViewData["configValue"] = ConfigurationManager.AppSettings["APIKey"]; return(View()); }
public async Task <string> GetSecretAsApplicationUsingManagedIdentityAsync() { logger.LogInformation("----- System Assigned Managed Identity"); SecretClientOptions options = KeyVaultUtility.CreateSecretClientOptions(); var credentialOptions = new DefaultAzureCredentialOptions { ExcludeAzureCliCredential = true, ExcludeInteractiveBrowserCredential = true, ExcludeSharedTokenCacheCredential = true, ExcludeEnvironmentCredential = true, ExcludeVisualStudioCredential = true, ExcludeVisualStudioCodeCredential = true }; var credentials = new DefaultAzureCredential(credentialOptions); var keyVault = keyVaultConfiguration.Url; var client = new SecretClient(new Uri(keyVault), credentials, options); KeyVaultSecret secret = null; try { secret = await client.GetSecretAsync(keyVaultConfiguration.SecretName); return(secret.Value); } catch (Exception ex) { logger.LogError(ex, "Failed to get secret as managed identity"); throw; } }
public async Task <string> GetSecretAsApplicationUsingClientCertificateAsync() { logger.LogInformation("----- Client Certificate Async"); SecretClientOptions options = KeyVaultUtility.CreateSecretClientOptions(); var keyVault = keyVaultConfiguration.Url; var credential = new ClientCertificateCredential( applicationConfiguration.TenantId, applicationConfiguration.ClientId, KeyVaultUtility.GetCertificate(applicationConfiguration.Thumbprint)); var client = new SecretClient(new Uri(keyVault), credential, options); KeyVaultSecret secret = null; try { secret = await client.GetSecretAsync(keyVaultConfiguration.SecretName); return(secret.Value); } catch (Exception ex) { logger.LogError(ex, "Failed to get secret as client sertificate"); throw; } }
public async Task <string> GetSecretAsApplicationUsingUserManagedIdentityAsync() { logger.LogInformation("----- User Assigned Managed Identity"); SecretClientOptions options = KeyVaultUtility.CreateSecretClientOptions(); var credentials = new ManagedIdentityCredential(keyVaultConfiguration.UserAssignedManagedIdentityClientId); var keyVault = keyVaultConfiguration.Url; var client = new SecretClient(new Uri(keyVault), credentials, options); KeyVaultSecret secret = null; try { secret = await client.GetSecretAsync(keyVaultConfiguration.SecretName); return(secret.Value); } catch (Exception ex) { logger.LogError(ex, "Failed to get secret as managed identity"); throw; } }
internal static string GetPw() { //This is for local use only, when secrets are not accessible. if (File.Exists("pw.txt")) { return(File.ReadAllText("pw.txt")); } var options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 2, Mode = RetryMode.Exponential } }; var client = new SecretClient(new Uri("https://backgammon-keys.vault.azure.net/"), new DefaultAzureCredential(), options); KeyVaultSecret secret = client.GetSecret("bgdbpw"); string secretValue = secret.Value; return(secretValue); }
public async Task TenantChangedRequest() { MockTransportBuilder builder = new MockTransportBuilder { AccessTokenLifetime = TimeSpan.Zero, }; MockTransport transport = builder.Build(); SecretClientOptions options = new SecretClientOptions { Transport = transport, }; MockCredential credential = new MockCredential(transport); SecretClient client = new SecretClient(VaultUri, credential, options); KeyVaultSecret secret = await client.GetSecretAsync("test-secret").ConfigureAwait(false); Assert.AreEqual("secret-value", secret.Value); builder.TenantId = "de763a21-49f7-4b08-a8e1-52c8fbc103b4"; try { await client.GetSecretAsync("test-secret").ConfigureAwait(false); Assert.Fail("Expected a 401 Unauthorized response"); } catch (RequestFailedException ex) when(ex.Status == 401) { } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; var client = new SecretClient(new Uri("https://ntmskv121.vault.azure.net/"), new DefaultAzureCredential(), options); KeyVaultSecret secret = client.GetSecret("mySecret"); string secretValue = secret.Value; app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync(secretValue); }); }); }
public static async Task Main(string[] args) { SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential, }, }; var client = new SecretClient(new Uri(KnownApplicationUrls.KeyVaultUrl), new DefaultAzureCredential(), options); KeyVaultSecret secret = client.GetSecret(KnownSecretNames.ServiceBusConnectionString); _serviceBusConnectionString = secret.Value; _topicName = args[0]; topicClient = new TopicClient(_serviceBusConnectionString, _topicName); string filePath = args[1]; int start = int.Parse(args[2]); int end = int.Parse(args[3]); file = File.ReadLines(filePath).Skip(start).Take(end - start).ToArray(); Console.WriteLine("======================================================"); Console.WriteLine("Press ENTER key to exit after sending all the messages."); Console.WriteLine("======================================================"); // Send messages. await SendAllMessagesAsync(); await topicClient.CloseAsync(); }
public static string GetDBConnectionString() { string strConnectionString = string.Empty; string keyvaultuse = ConfigurationManager.AppSettings["DBCONSTRFROMAZKEYVAULT"].ToString(); if (keyvaultuse.ToUpper() == "TRUE") { string BASESECRETURI = ConfigurationManager.AppSettings["KeyVaultURL"].ToString(); SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; var client = new SecretClient(new Uri(BASESECRETURI), new DefaultAzureCredential(), options); KeyVaultSecret secret = client.GetSecret("academydbconstr"); strConnectionString = secret.Value; } else { strConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString; } return(strConnectionString); }
/// <summary> /// Initializes a new instance of the type /// </summary> /// <param name="keyVault">The key vault URI</param> /// <param name="credential">Oauth token credentials</param> /// <param name="options">The options used to access the secrets</param> public KeyVaultSecrets(Uri keyVault, TokenCredential credential, SecretClientOptions options) { Guard.NotNull(nameof(credential), credential); Guard.NotNull(nameof(options), options); Guard.NotNull(nameof(keyVault), keyVault); Client = new SecretClient(keyVault, credential, options); }
/// <summary> /// Configures the retries on an options instance /// </summary> /// <param name="options">The options instance</param> /// <param name="mode">The retry mode</param> /// <param name="maximumRetries">The maximum retries to be performed</param> /// <param name="delay">The delay before invoking the first retry</param> /// <param name="maximumDelay">The maximum delay allowed between retries</param> /// <param name="networkTimeout">The network timeout for a single operation</param> public static void ConfigureRetries(SecretClientOptions options, RetryMode mode, int maximumRetries, TimeSpan delay, TimeSpan maximumDelay, TimeSpan networkTimeout) { options.Retry.Delay = delay; options.Retry.MaxDelay = maximumDelay; options.Retry.MaxRetries = maximumRetries; options.Retry.NetworkTimeout = networkTimeout; options.Retry.Mode = mode; }
public void AddingPerCallPolicy() { #region Snippet:AddingPerCallPolicy SecretClientOptions options = new SecretClientOptions(); options.AddPolicy(new CustomRequestPolicy(), HttpPipelinePosition.PerCall); options.AddPolicy(new StopwatchPolicy(), HttpPipelinePosition.PerRetry); #endregion }
public SecretClientTests(bool isAsync) : base(isAsync) { SecretClientOptions options = new SecretClientOptions { Transport = new MockTransport(), }; Client = InstrumentClient(new SecretClient(new Uri("http://localhost"), new DefaultAzureCredential(), options)); }
/// <summary> /// Configures the diagnostics information associated with a credential option /// </summary> /// <param name="options">The option instance</param> /// <param name="applicationId">The application id</param> /// <param name="isDistributedTracingEnabled">True if distributed tracing is in use</param> /// <param name="isLoggingContentEnabled">True if logging of content is enabled</param> /// <param name="isLoggingEnabled">True if logging is enabled</param> /// <param name="isTelemetryEnabled">True if telemetry is enabled</param> /// <param name="loggingContentSizeLimit">The maximum size of the content being logged</param> public static void ConfigureDiagnostics(SecretClientOptions options, string applicationId, bool isDistributedTracingEnabled, bool isLoggingContentEnabled, bool isLoggingEnabled, bool isTelemetryEnabled, int loggingContentSizeLimit) { options.Diagnostics.ApplicationId = applicationId; options.Diagnostics.IsDistributedTracingEnabled = isDistributedTracingEnabled; options.Diagnostics.IsLoggingContentEnabled = isLoggingContentEnabled; options.Diagnostics.IsLoggingEnabled = isLoggingEnabled; options.Diagnostics.IsTelemetryEnabled = isTelemetryEnabled; options.Diagnostics.LoggedContentSizeLimit = loggingContentSizeLimit; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), // Mode = RetryMode.Exponential, MaxRetries = 5 } }; string secretValue = null; try { // If running in kubernetes if (standAloneContainer == false) { var client = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential(), options); KeyVaultSecret secret = client.GetSecret(dbCredentials); secretValue = secret.Value; } else { secretValue = "The app running locally on a container cannot access the appsettings.json inside config folder which is created by k8s configmap"; } } catch (Exception ex) { secretValue = "Cannot access key vault. " + Environment.NewLine + ex.Message; } app.UseEndpoints(endpoints => { // Set up the response for base path endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World from a .Net core web app!!!"); }); // Set up the response to demonstrate Azure Key Vault endpoints.MapGet("/keyvault", async context => { await context.Response.WriteAsync(secretValue); }); }); }
public SecretTest(TOptions options) : base(options) { var keyvaultUri = GetEnvironmentVariable("KEYVAULT_URI"); var secretClientOptions = new SecretClientOptions() { Transport = PerfStressTransport.Create(options) }; SecretClient = new SecretClient(new Uri(keyvaultUri), new DefaultAzureCredential(), secretClientOptions); }
public static void LoggingContent() { #region Snippet:LoggingContent SecretClientOptions options = new SecretClientOptions() { Diagnostics = { IsLoggingContentEnabled = true } }; #endregion }
public static void DisablingLogging() { #region Snippet:DisablingLogging SecretClientOptions options = new SecretClientOptions() { Diagnostics = { IsLoggingEnabled = false } }; #endregion }
public void SettingHttpClient() { #region Snippet:SettingHttpClient using HttpClient client = new HttpClient(); SecretClientOptions options = new SecretClientOptions { Transport = new HttpClientTransport(client) }; #endregion }
public static void LoggingRedactedHeader() { #region Snippet:LoggingRedactedHeader SecretClientOptions options = new SecretClientOptions() { Diagnostics = { LoggedHeaderNames = { "x-ms-request-id" }, LoggedQueryParameters = { "api-version" } } }; #endregion }
public static void LoggingRedactedHeaderAll() { #region Snippet:LoggingRedactedHeaderAll SecretClientOptions options = new SecretClientOptions() { Diagnostics = { LoggedHeaderNames = { "*" }, LoggedQueryParameters = { "*" } } }; #endregion }
public async Task SingleRequest() { MockTransport transport = new MockTransportBuilder().Build(); SecretClientOptions options = new SecretClientOptions { Transport = transport, }; SecretClient client = new SecretClient(VaultUri, new MockCredential(transport), options); KeyVaultSecret secret = await client.GetSecretAsync("test-secret").ConfigureAwait(false); Assert.AreEqual("secret-value", secret.Value); }
static void test() { const string keyVaultName = "key-vault-test02"; const string AZURE_TENANT_ID = "d99eee11-8587-4c34-9201-xxxxxxxxxxxx"; const string AZURE_CLIENT_ID = "80f16cbd-e549-4c93-9e7b-xxxxxxxxxxxx"; const string AZURE_CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; ClientSecretCredential credential = new ClientSecretCredential(AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET); var kvUri = String.Format("https://{0}.vault.azure.net", keyVaultName); SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(5), MaxDelay = TimeSpan.FromSeconds(15), MaxRetries = 5, Mode = RetryMode.Exponential } }; var client = new SecretClient(new Uri(kvUri), credential, options); //new DefaultAzureCredential() for authenticating VM string secretName = "secret003"; string secretValue = "123456"; //Console.ReadLine(); Console.Write("Creating a secret in " + keyVaultName + " called '" + secretName + "' with the value '" + secretValue + "` ..."); client.SetSecret(secretName, secretValue); Console.WriteLine(" done."); Console.WriteLine("Forgetting your secret."); secretValue = ""; Console.WriteLine("Your secret is '" + secretValue + "'."); Console.WriteLine("Retrieving your secret from " + keyVaultName + "."); KeyVaultSecret secret = client.GetSecret(secretName); Console.WriteLine("Your secret is '" + secret.Value + "'."); Console.Write("Deleting your secret from " + keyVaultName + " ..."); client.StartDeleteSecret(secretName); System.Threading.Thread.Sleep(5000); Console.WriteLine(" done."); }
public ApiKeyService() { SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; client = new SecretClient(new Uri("https://steamachievementtracker.vault.azure.net/"), new DefaultAzureCredential(), options); }
public BasicKeyVaultClient() { SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; this.Client = new SecretClient(new Uri("https://omgspiderskv.vault.azure.net/"), new DefaultAzureCredential(), options); }
public KeyVaultService(SecretClientOptions options = null) { SecretClientOptions defaultOptions = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential } }; client = new SecretClient(new Uri("https://PlayStationWishlistKV.vault.azure.net/"), new DefaultAzureCredential(), options ?? defaultOptions); }
public static async Task Main(string[] args) { EnsureArg.IsNotNull(args, nameof(args)); var options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), MaxRetries = 5, Mode = RetryMode.Exponential, }, }; var client = new SecretClient(new Uri(KnownApplicationUrls.KeyVaultUrl), new DefaultAzureCredential(), options); KeyVaultSecret secret = await client.GetSecretAsync(KnownSecretNames.BlobStoreConnectionString); s_containerConnectionString = secret.Value; string filepath = args[0]; var container = new BlobContainerClient(s_containerConnectionString, ContainerName); int i = 0; var studies = new HashSet <string>(); var series = new HashSet <string>(); using (var sw = new StreamWriter(filepath)) { await foreach (BlobItem blob in container.GetBlobsAsync()) { string[] parsedInstanceName = blob.Name.Split(KnownSeparators.MessageSeparators, StringSplitOptions.RemoveEmptyEntries); studies.Add(parsedInstanceName[0]); series.Add(parsedInstanceName[0] + " " + parsedInstanceName[1]); await sw.WriteLineAsync(blob.Name); i++; Console.WriteLine(blob.Name + " Count:" + i); } } string seriesPath = args[1]; File.WriteAllLines(seriesPath, series); string studiesPath = args[2]; File.WriteAllLines(studiesPath, studies); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); SecretClientOptions options = new SecretClientOptions() { Retry = { Delay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(16), // Mode = RetryMode.Exponential, MaxRetries = 5 } }; string secretValue = null; try { var client = new SecretClient(new Uri("https://kv-abs.vault.azure.net/"), new DefaultAzureCredential(), options); KeyVaultSecret secret = client.GetSecret("db-credentials"); secretValue = secret.Value; } catch (System.Exception ex) { secretValue = "Cannot access key vault. " + Environment.NewLine + ex.Message; } app.UseEndpoints(endpoints => { // Set up the response for base path endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World from a .Net core web app!!!"); }); // Set up the response to demonstrate Azure Key Vault endpoints.MapGet("/keyvault", async context => { await context.Response.WriteAsync(secretValue); }); }); }