Azure 密钥保管库未从应用设置中检索客户端 ID 或客户端机密



我正在尝试从我的 ASP.NET MVC Web 应用程序中使用 Azure 密钥保管库,我正在按照这些说明进行操作。

我的 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 应用程序的应用程序设置中,就像说明中显示的屏幕截图一样。由于我这样做了,我可以期待(从说明中(:

如果你有 Azure Web 应用,现在可以在 Azure 门户中添加应用设置的实际值。通过这样做,实际值将不会在 web.config 中,而是通过具有单独访问控制功能的门户进行保护。这些值将替换为您在 web.config 中输入的值。确保名称相同。

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


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

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

最新更新