Debugging 403 and login failures from Azure-hosted .NET apps to Key Vault, Azure SQL and Storage: which identity is used, managed identity configuration, data-plane RBAC, Key Vault access policy vs RBAC mode, contained SQL users, firewalls and private endpoints, and propagation delays.
On a laptop, DefaultAzureCredential uses my az login identity, which has broad dev rights. In Azure it uses the app's managed identity, which may not exist, may be the wrong one, or may lack roles. I diagnose in layers:
AZURE_CLIENT_ID set?ForbiddenByRbac means missing Key Vault Secrets User (or the vault uses access policies). SQL's <token-identified principal> means the token worked but there is no contained database user.ForbiddenByFirewall or ForbiddenByConnection means firewall or private endpoint and DNS problems.The trade-off: granting broad roles makes the error go away fast but breaks least privilege; the right fix is the exact data role at the exact scope.
"The first thing I remind myself is that it works locally for the wrong reason.
DefaultAzureCredentialon my machine picks up my Azure CLI or Visual Studio sign-in, and I'm probably an admin on the dev resources. In App Service it falls through to managed identity, so the question becomes: is there an identity, is it the one I think, does it have the right data-plane role, and can it reach the endpoint over the network? I work through those in order, and I let the error code tell me which layer is failing.For example, at [company] we [moved an API to a new subscription] and it failed at startup with a Key Vault 403. The error body said
ForbiddenByRbac, so authentication worked and authorisation didn't.az role assignment list --assignee <principalId> --allshowed the identity had Reader on the vault, which is control plane only. The new vault was also in RBAC mode while the old one used access policies, so the old access policy we'd copied did nothing. I granted Key Vault Secrets User on the vault in Bicep, and after a few minutes the app started. Then SQL failed withLogin failed for user '<token-identified principal>'. That message means Entra issued a valid token but the database has no user for that identity, so I ranCREATE USER [app-orders-prod] FROM EXTERNAL PROVIDERand added it todb_datareaderanddb_datawriter. [It took about N minutes end to end once we knew which layer was failing.]If the error had been
ForbiddenByFirewallor SQL error 47073 about public network access, I'd have looked at networking: firewall rules, private endpoints and whether the app resolves the private IP. The mistake I see is people granting Owner or switching back to a connection string to make it work. Each error code points at one layer, so read it before changing anything."
| Service | Error | Layer | Usual fix |
|---|---|---|---|
| Key Vault | 401, CredentialUnavailableException in logs |
No identity | Enable managed identity; set AZURE_CLIENT_ID for user-assigned |
| Key Vault | 403 ForbiddenByRbac |
RBAC | Key Vault Secrets User on the vault |
| Key Vault | 403 AccessDenied (access policy mode) |
Access policy | Add an access policy, or move the vault to RBAC |
| Key Vault | 403 ForbiddenByFirewall |
Network | Add the app's outbound path, or use a private endpoint |
| Key Vault | 403 ForbiddenByConnection |
Network | Public access disabled; fix private endpoint and DNS |
| Azure SQL | 18456, <token-identified principal> |
Database user | CREATE USER ... FROM EXTERNAL PROVIDER + roles |
| Azure SQL | 40615, client IP not allowed | Firewall | Firewall rule, or private endpoint |
| Azure SQL | 47073, deny public network access | Network | Private endpoint and private DNS |
| Storage | 403 AuthorizationPermissionMismatch |
RBAC | Storage Blob Data Reader/Contributor |
| Storage | 403 AuthorizationFailure |
Network or shared key disabled | Firewall, private endpoint, or use Entra auth |
In one migration, three of four 403 errors came from roles copied at the wrong scope or as control-plane roles, and one from a vault switched to RBAC mode. Reading the error codes first cut time to resolve from [most of a day of trial and error] to under an hour.
Checks that the candidate debugs Azure access failures methodically by layer instead of granting broad permissions.
Green flags
Red flags
[1] Which identity? ─▶ [2] Token issued? ─▶ [3] Network path allowed? ─▶ [4] Authorised on the data plane?
MI enabled, Entra sign-in firewall, public access, RBAC role / access policy /
right client id logs private endpoint + DNS SQL contained user
A failure at layer 1 shows up as CredentialUnavailableException or AuthenticationFailedException in the app. Layers 3 and 4 show up as 403s from the service with different codes. SQL is special: network failures and missing users are different SQL error numbers.
Turn on Azure SDK logging to see which credentials DefaultAzureCredential tried and why each failed:
using Azure.Core.Diagnostics;
using var listener = AzureEventSourceListener.CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel.Verbose);
In ASP.NET Core, setting the Azure.Identity and Azure.Core log categories to Debug routes the same events through ILogger. From the Kudu console you can request a token directly from $IDENTITY_ENDPOINT and decode it to check oid, appid and aud.
| Role | Plane | Can read secrets or blobs? |
|---|---|---|
| Owner, Contributor, Reader | Control | No |
| Key Vault Secrets User | Data | Read secrets |
| Storage Blob Data Reader | Data | Read blobs |
A vault has one permission model: Azure RBAC or legacy access policies. In RBAC mode access policies are ignored; in access policy mode, data-plane RBAC roles are ignored. Teams copying setups between vaults often get this wrong.
Role assignments usually take effect within minutes (up to about 10). The managed identity's tokens are cached by the SDK and the platform, so changes through Entra group membership can take hours to show up. During debugging, assign roles directly to the identity, then move to groups once it works.
nslookup <name> from Kudu: a public IP means private DNS isn't linked.AZKVAuditLogs or AzureDiagnostics) show caller identity, operation, result and reason.StorageBlobLogs) show AuthenticationType and status.ForbiddenByConnection.Make failures diagnosable: an explicit credential in Azure, SDK logging, and a startup check that reports which layer failed.
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
var builder = WebApplication.CreateBuilder(args);
// Explicit in Azure, so a missing identity fails clearly instead of falling through the chain.
TokenCredential credential = builder.Environment.IsDevelopment()
? new DefaultAzureCredential()
: new ManagedIdentityCredential(
ManagedIdentityId.FromUserAssignedClientId(builder.Configuration["AZURE_CLIENT_ID"]!));
var app = builder.Build();
// Optional diagnostic endpoint (internal only) that reports which layer fails.
app.MapGet("/diag/keyvault", async (IConfiguration config, ILogger<Program> logger, CancellationToken ct) =>
{
var client = new SecretClient(new Uri(config["KeyVault:Uri"]!), credential);
try
{
await client.GetSecretAsync("diag-probe", cancellationToken: ct);
return Results.Ok("ok");
}
catch (CredentialUnavailableException ex)
{
logger.LogError(ex, "No managed identity available"); // layer 1
return Results.Problem("identity: " + ex.Message);
}
catch (RequestFailedException ex) when (ex.Status == 403)
{
// ErrorCode distinguishes RBAC (ForbiddenByRbac) from network (ForbiddenByFirewall / ForbiddenByConnection).
logger.LogError(ex, "Key Vault denied: {ErrorCode}", ex.ErrorCode);
return Results.Problem($"keyvault 403: {ex.ErrorCode}");
}
}).RequireHost("localhost"); // never expose diagnostics publicly
app.Run();
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Azure.Identity": "Debug",
"Azure.Core": "Warning"
}
}
}
# Which identity does the app have, and what can it do?
az webapp identity show -g rg-orders-prod-aue -n app-orders-prod-aue
az role assignment list --assignee <principalId> --all -o table
# Is the vault in RBAC mode?
az keyvault show -n kv-orders-prod-aue --query properties.enableRbacAuthorization
-- Fix for "Login failed for user '<token-identified principal>'"
CREATE USER [app-orders-prod-aue] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [app-orders-prod-aue];
ALTER ROLE db_datawriter ADD MEMBER [app-orders-prod-aue];
CredentialUnavailableException, or DefaultAzureCredential falls through to nothing. Instead: Enable the identity in IaC alongside the app and check it with az webapp identity show.CREATE USER ... FROM EXTERNAL PROVIDER and add database roles.enableRbacAuthorization and standardise on RBAC.The senior habit is to make these failures self-explanatory before they happen: an explicit credential in Azure, Azure SDK logs at Debug for Azure.Identity during rollout, role assignments and SQL users created by the same pipeline that deploys the app, and a smoke test after deploy that touches each dependency. Then a 403 is a pipeline failure in staging, not a production outage.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Roles and SQL users in IaC/pipeline | All environments | Pipeline needs rights to assign roles | Never skip it |
| Post-deploy smoke test per dependency | Every release | A few seconds per deploy | None |
| Diagnostic endpoint | Internal debugging | Must be locked down | Public exposure |
| Temporary broad role | Never in production | Security risk | Always |
I measure it by dependency failure rates in Application Insights after each deploy and by Key Vault audit logs showing zero denied calls from production identities.
Managed identity gives the app an Entra ID identity that Azure manages, so there is no secret to store or rotate. In code, Azure.Identity gets tokens: DefaultAzureCredential tries managed identity in Azure and the developer's az login or Visual Studio sign-in locally. Then:
AddAzureKeyVault.BlobServiceClient with the credential.CREATE USER [app-name] FROM EXTERNAL PROVIDER, add it to database roles, and use Authentication=Active Directory Default in the connection string.Use a user-assigned identity when several apps share access or it must survive redeploys. The trade-off is setup effort in RBAC and SQL users in exchange for no secrets at all.
I build it in layers:
The trade-off is cost and complexity (private DNS, more resources) versus a much smaller attack surface and a tested recovery path.
Use Microsoft Entra ID authentication with a managed identity. Steps: 1. set a Microsoft Entra admin on the Azure SQL logical server (optionally enable Microsoft Entra-only authentication to turn off SQL logins); 2. turn on a system- or user-assigned managed identity on the App Service, Container App or AKS workload; 3. connected as the Entra admin, create a contained user for it in the database, CREATE USER [my-api] FROM EXTERNAL PROVIDER;, and grant least privilege (db_datareader, db_datawriter, no DDL for the app); 4. use a connection string with Authentication=Active Directory Default (or Active Directory Managed Identity plus User Id=<client id> for a user-assigned identity). Microsoft.Data.SqlClient gets and refreshes tokens itself, so EF Core needs no code change, and locally the same string uses your Azure CLI or Visual Studio sign-in. No secret exists to leak or rotate.
How to tell it (STAR)
**S:** We moved our orders API to a new subscription during a [two-hour] window, and it failed at startup with a Key Vault 403. **T:** I had to get it running without falling back to secrets. **A:** The error code was `ForbiddenByRbac`, and the new vault was in RBAC mode, so our copied access policy did nothing; the identity only had Reader. I added *Key Vault Secrets User* through the pipeline. Then SQL said token-identified principal, which meant no contained user, so I created it with read and write roles. **R:** We were live [40 minutes] into the window, and with the roles, SQL user and a smoke test now in the pipeline, the next [three] environment moves had no access failures.
Last updated 23 Nov 2026.