.NET Framework4.7.2非MVC Web应用本地连接Azure Key Vault失败
如何让Azure Key Vault在VS2019/2022中与.NET Framework4.7.2非MVC Web应用(带web.config)协同工作?
问题背景
需为.NET Framework4.7.2的非MVC Web应用(依赖web.config)配置Azure Key Vault,此前同版本旧站点曾正常运行但近期失效,新站点部署时遭遇认证权限问题。已按微软官方教程完成以下操作:
- 配置web.config(片段如下)
- 更新至最新NuGet包:Azure.Core 1.28.2、Azure.Identity 1.8.2、Azure.Security.KeyVault.Keys 4.4.0、Azure.Security.KeyVault.Secrets 4.4.0
- 创建Azure Key Vault实例
- 为VS登录的个人账号授予Key Vault完全访问权限
已配置的web.config片段
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" /> </configSections> <configBuilders> <builders> <add name="AzureKeyVault" vaultName="TestVault" type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Azure, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </builders> </configBuilders> <connectionStrings configSource="ConnectionStrings.config" /> <appSettings configBuilders="AzureKeyVault"> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <!-- Site Settings --> <add key="TestSecret" value="" /> </appSettings> ... </configuration>
遇到的错误
处理appSettings配置节时configBuilder 'AzureKeyVault'失败,根源为Azure CLI认证失败,提示访问C:\WINDOWS\system32\config\systemprofile\.azure时权限被拒绝(WinError 5)。
解决方案
1. 强制使用Visual Studio身份认证(推荐)
修改web.config中AzureKeyVault配置节点,添加credentialType="VisualStudio"属性,直接使用VS登录账号认证,绕开Azure CLI权限问题:
<add name="AzureKeyVault" vaultName="TestVault" type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Azure, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" credentialType="VisualStudio" />
2. 安装缺失的核心配置构建器NuGet包
确保安装Microsoft.Configuration.ConfigurationBuilders.Azure包,这是Azure Key Vault配置构建器的核心依赖,此前可能仅安装Azure SDK相关包而遗漏此包。
3. 授予系统账户访问.azure目录的权限
- 打开文件资源管理器,导航到
C:\WINDOWS\system32\config\systemprofile - 若
.azure文件夹不存在,右键创建该文件夹 - 右键
.azure文件夹 →「属性」→「安全」→「编辑」→「添加」 - 输入
IIS AppPool\DefaultAppPool,点击「检查名称」确认后添加 - 为该账户授予「读取和写入」权限,保存设置
4. 修改IIS Express运行身份
- 在VS中右键项目 →「属性」→「Web」
- 在「服务器」区域,点击IIS Express旁的「...」按钮
- 进入「应用程序池」→「高级设置」
- 将「进程模型」下的「标识」改为当前登录用户或「本地系统」(选择当前用户需输入账户密码)
- 重启VS和项目
内容的提问来源于stack exchange,提问作者RoLYroLLs
相关产品推荐
相关产品推荐

