将 azure keyvault secret json 反序列化为 MicrosoftIdentityOptions

Deserializing azure keyvault secret json to MicrosoftIdentityOptions

我在应用程序启动时加载密钥保管库机密并且配置添加了保管库机密 as we can see here。 我正在使用 Microsoft.Identity.Web 添加 AD SSO 并注册示例中提到的 AddSignin()。但是秘密并没有像预期的那样被序列化 at this point。但是,如果秘密保存在 appsettings.json 中,它就可以正常工作。我怎样才能使这项工作?需要显式反序列化吗?

请在下面找到完整的代码设置

1.Program.cs 有以下代码。

ConfigureAppConfiguration((hostingCtx, config) =>
        {

            if (hostingCtx.HostingEnvironment.IsProduction())
            {
                var builtConfig = config.Build();
                AzureKeyVaultConfigurationExtensions.AddAzureKeyVault(config, builtConfig["AppConfiguration:KeyVaultUrl"]);
            }
        })
  1. 以下json格式的秘密存储在keyvault
{"CallbackPath":"/home/index","ClientId":"######","ClientSecret":"#######","Domain":"######","Instance":"######","TenantId":"######"}
  1. 添加了对 Microsoft.Identity.Web 的引用

  2. 在Startup.cs->ConfigureService

  3. 中注册了以下服务
    services.AddAuthentication(sharedOptions =>
                {
                    sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                })
                .AddSignIn("AzureAd1", configuration, options => configuration.Bind("AzureAd1", options));
  1. 应用程序 bootstrap 下面的变量 microsoftIdentityOptions 为 null

文件 - WebAppServiceCollectionExtensions.cs

public static AuthenticationBuilder AddSignIn(
                this AuthenticationBuilder builder,
                string configSectionName,
                IConfiguration configuration,
                string openIdConnectScheme,
                string cookieScheme,
                Action<OpenIdConnectOptions> configureOptions,
                bool subscribeToOpenIdConnectMiddlewareDiagnosticsEvents = false)
            {
                builder.Services.Configure(openIdConnectScheme, configureOptions);
                builder.Services.Configure<MicrosoftIdentityOptions>(options => configuration.Bind(configSectionName, options));

                var microsoftIdentityOptions = configuration.GetSection(configSectionName).Get<MicrosoftIdentityOptions>();
     .......
     ......
    }

非常感谢任何帮助。

谢谢

答案就在这里https://docs.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-2.2#bind-an-array-to-a-class

Create secrets in the key vault as name-value pairs.

Azure Key Vault secret names are limited to alphanumeric characters and dashes. Hierarchical values (configuration sections) use -- (two dashes) as a separator. Colons, which are normally used to delimit a section from a subkey in ASP.NET Core configuration, aren't allowed in key vault secret names. Therefore, two dashes are used and swapped for a colon when the secrets are loaded into the app's configuration.

与其将所有秘密保存在一个 json 中,不如将每个 属性 作为一个秘密添加。

例如“AzureAd1--TenantId”应该是 AzureAd1 表示部分的键的名称