C#C
C#2y ago
Ryalia

Clone

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.AddAzureClients();
        var secretClient = AzureKeyVaultExtensions.GetSecretClient(builder.Configuration);

        builder.Services.AddGoogleOpenIdConnect(
            options => // options...
        )
    }
}

public static class AzureKeyVaultExtensions
{
    public static void AddAzureClients(this WebApplicationBuilder builder)
    {
        builder.Services.AddAzureClients(clientBuilder =>
        {
            clientBuilder.AddClient<SecretClient, SecretClientOptions>(_ => GetSecretClient(builder.Configuration));
        });
    }

    public static SecretClient GetSecretClient(IConfiguration configuration)
    {
        var azureConfiguration = GetConfiguration(configuration);
        var uri = new Uri(azureConfiguration.Url);
        var clientSecretCredential = GetCredential(azureConfiguration);
        return new SecretClient(uri, clientSecretCredential);
    }

    private static ClientSecretCredential GetCredential(AzureKeyVaultConfiguration azureConfiguration)
    {
        return new ClientSecretCredential(
            azureConfiguration.DirectoryId,
            azureConfiguration.ClientId,
            azureConfiguration.ClientSecret
        );
    }

    private static AzureKeyVaultConfiguration GetConfiguration(IConfiguration configuration)
    {
        return configuration
            .GetRequiredSection($"Authentication:{AzureKeyVaultConfiguration.SectionName}")
            .Get<AzureKeyVaultConfiguration>()
            ?? throw new ApplicationException("Azure Key Vault Configuration is not set");
    }
}


{
  "Authentication": {
    "AzureKeyVault": {
      "Url": "https://<sensitive>.vault.azure.net/",
      "ClientId": "<sensitive>",
      "ClientSecret": "<sensitive>",
      "DirectoryId": "<sensitive>"
    }
  }
}
Was this page helpful?