Azure Function中无法检索密钥:访问被拒绝(附相关代码)
Let's walk through the most common causes and fixes for this access denied issue—these steps should help you get your function working with Key Vault again:
1. Verify Managed Identity is Enabled
First, make sure your Azure Function has a managed identity set up:
- Head to your Function App in the Azure Portal, go to the Identity tab.
- For system-assigned identity: Check if the status is set to On. If not, toggle it on and save.
- For user-assigned identity: Ensure you've created a user-assigned managed identity and linked it to your Function App here.
2. Check Key Vault Access Policies
Your managed identity needs explicit permissions to read secrets from Key Vault:
- Go to your Key Vault in the Azure Portal, navigate to Access Policies.
- Click Add Access Policy, then under Configure from template, select Secret Management (or manually check the Get permission under Secret Permissions).
- Under Select Principal, search for your Function App's name (for system-assigned identity) or your user-assigned identity's name, select it, then save the policy.
- Note: Access policy changes can take 5-10 minutes to propagate, so wait a bit before retesting.
3. Validate Key Vault Client Initialization
Double-check that your KeyVaultClient is initialized correctly with the token provider. Here's the complete working snippet:
AzureServiceTokenProvider tokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(async (authority, resource, scope) => { var token = await tokenProvider.GetAccessTokenAsync("https://vault.azure.net"); return token; });
Make sure you're passing the correct resource URI (https://vault.azure.net) to GetAccessTokenAsync—this is critical for authenticating to Key Vault.
4. Check Key Vault Network Restrictions
If your Key Vault has firewall or VNet restrictions enabled, your Function might be blocked:
- Go to Key Vault's Networking tab.
- If you're using a Consumption plan Function, enable the Allow trusted Microsoft services to bypass this firewall option.
- If your Function is in a dedicated plan with VNet integration, add your Function's VNet/subnet to the allowed list under Virtual networks.
5. Dig into Detailed Logs
If you're still stuck, check Application Insights logs for your Function App. Look for specific error messages like:
Identity not found: Indicates the managed identity isn't set up correctly.Permission denied: Confirms the access policy is missing the required permissions.
These logs will give you precise clues to narrow down the issue.
内容的提问来源于stack exchange,提问作者Randy Minder

