Azure Key Vault 未从应用程序设置中检索 ClientId 或 ClientSecret

Azure Key Vault not retrieving ClientId or ClientSecret from App Settings

我正在尝试从我的 ASP.NET MVC Web 应用程序中使用 Azure Key Vault,并且我正在关注 these instructions

我的 Web.config 看起来像这样(与说明中的相同):

<!-- ClientId and ClientSecret refer to the web application registration with Azure Active Directory -->
<add key="ClientId" value="clientid" />
<add key="ClientSecret" value="clientsecret" />

<!-- SecretUri is the URI for the secret in Azure Key Vault -->
<add key="SecretUri" value="secreturi" />

我获取访问令牌的方法如下所示(与说明相同):

//add these using statements
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;
using System.Web.Configuration;

//this is an optional property to hold the secret after it is retrieved
public static string EncryptSecret { get; set; }

//the method that will be provided to the KeyVaultClient
public static async Task<string> GetToken(string authority, string resource, string scope)
{
    var authContext = new AuthenticationContext(authority);
    ClientCredential clientCred = new ClientCredential(WebConfigurationManager.AppSettings["ClientId"],
            WebConfigurationManager.AppSettings["ClientSecret"]);
    AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);

    if (result == null)
        throw new InvalidOperationException("Failed to obtain the JWT token");

    return result.AccessToken;
}

我已将我的 ClientId、ClientSecret 和 SecretUri 放入我的 Web 应用程序的应用程序设置中,就像说明中的屏幕截图所示。由于我这样做了,我可以期待(从说明中):

If you have an Azure Web App, you can now add the actual values for the AppSettings in the Azure portal. By doing this, the actual values will not be in the web.config but protected via the Portal where you have separate access control capabilities. These values will be substituted for the values that you entered in your web.config. Make sure that the names are the same.

但是,当我 运行 上面的方法时,WebConfigurationManager.AppSettings["ClientId"] 的值解析为 clientid 这是虚拟值,对于 ClientSecret 也是如此。我的理解是该方法应该连接到 Azure 门户中的 Web 应用程序并替换值。 我错过了什么?为什么不替换值?


编辑:另外,我使用 Azure Active Directory B2C 而不是 Azure Active Directory 可能很重要。

当您 运行 或从本地环境调试应用程序时,应用程序会从 web.config 中选取值,因此您会在网页上看到虚拟值。当您将应用程序部署到 Azure 时,您的应用程序将从 Azure 应用程序设置中选取值。此外,您需要在 web.config 以及 Azure 应用程序设置中保持密钥名称相同。希望这有帮助。