📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your .NET 10 API works on your laptop, but after deploying to Azure App Service it fails at startup with 403 Forbidden from Key Vault, and later calls to Azure SQL fail with "Login failed for user '<token-identified principal>'". How do you diagnose identity, RBAC and network problems step by step, and fix them properly?

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.

Senior Debugging Advanced azure debugging devops key-vault managed-identity rbac

🎯 Key points

  • DefaultAzureCredential tries environment, workload identity and managed identity before developer tools; on a laptop no managed identity exists, so your az login wins
  • Read the exact error code: ForbiddenByRbac, AccessDenied, ForbiddenByFirewall, ForbiddenByConnection
  • Confirm the identity is enabled and is the right one (AZURE_CLIENT_ID for user-assigned), and list its effective role assignments
  • Data-plane role at the right scope (not Owner, Contributor or Reader), and Key Vault permission model (RBAC vs access policies)
  • Azure SQL: 'token-identified principal' means no contained user; CREATE USER FROM EXTERNAL PROVIDER
  • Network: firewall rules, public access disabled, private endpoint DNS
  • Role propagation takes minutes; group membership changes for managed identities can take hours
  • Evidence from Azure.Identity Debug logs, Key Vault audit logs, SQL auditing and Entra managed identity sign-in logs

⏱ 30-second answer

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:

  1. Which identity? Is managed identity enabled, and for user-assigned, is AZURE_CLIENT_ID set?
  2. Authorisation: read the error code. Key Vault 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.
  3. Network: 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing I remind myself is that it works locally for the wrong reason. DefaultAzureCredential on 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> --all showed 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 with Login 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 ran CREATE USER [app-orders-prod] FROM EXTERNAL PROVIDER and added it to db_datareader and db_datawriter. [It took about N minutes end to end once we knew which layer was failing.]

If the error had been ForbiddenByFirewall or 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."


Error codes and what they mean

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate debugs Azure access failures methodically by layer instead of granting broad permissions.

Green flags

  • Explains why it works locally (developer credential in the chain)
  • Uses the exact error code to pick the layer (RBAC, access policy, network, SQL user)
  • Knows the token-identified principal message means a missing contained user
  • Mentions propagation delays and the logs that show the real cause

Red flags

  • Grants Owner or falls back to secrets
  • Doesn't know control-plane vs data-plane roles
  • Changes many settings at once with no evidence

📚 Learn in depth

1. The four layers

[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.

2. Seeing what the credential does

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.

3. Control plane vs data plane

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.

4. Propagation and caching

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.

5. Network checks

  • nslookup <name> from Kudu: a public IP means private DNS isn't linked.
  • Key Vault and Storage firewalls: App Service outbound IPs change across scale units; prefer VNet integration plus service or private endpoints.
  • SQL: 'Allow Azure services' is broad and not a substitute for private endpoints.

6. Logs that tell the truth

  • Key Vault audit logs (AZKVAuditLogs or AzureDiagnostics) show caller identity, operation, result and reason.
  • Entra sign-in logs → Managed identity sign-ins show whether a token was issued.
  • Storage logs (StorageBlobLogs) show AuthenticationType and status.
  • SQL auditing shows failed logins and the principal name.

Try it yourself

  1. Deploy an app with a system-assigned identity but no roles, and capture the exact Key Vault error body.
  2. Grant Reader on the vault and confirm it still fails; then grant Key Vault Secrets User and time propagation.
  3. Connect to Azure SQL with a token for an identity with no contained user and read the 18456 error.
  4. Disable public network access on the vault and observe ForbiddenByConnection.

💻 Code

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];

⚠ Common mistakes

  • Mistake: Deploying code that relies on managed identity without enabling the identity on the App Service (or on the new slot or environment). Why it is wrong: There is no identity endpoint, so the credential fails with CredentialUnavailableException, or DefaultAzureCredential falls through to nothing. Instead: Enable the identity in IaC alongside the app and check it with az webapp identity show.
  • Mistake: Granting Owner or Contributor to make the 403 go away. Why it is wrong: They are control-plane roles that don't grant data access, and they give far too much power. Instead: Grant the specific data role on the specific resource.
  • Mistake: Changing several things at once. Why it is wrong: You can't tell which change fixed it, and you leave extra permissions behind. Instead: Read the error code, fix one layer, test, then clean up.
  • Mistake: Assuming an RBAC role gives Azure SQL database access. Why it is wrong: The database needs a contained user for the identity. Instead: CREATE USER ... FROM EXTERNAL PROVIDER and add database roles.
  • Mistake: Copying access policies to a vault in RBAC mode, or roles to a vault in access policy mode. Why it is wrong: The vault ignores the other model. Instead: Check enableRbacAuthorization and standardise on RBAC.
  • Mistake: Falling back to a connection string or client secret. Why it is wrong: It reintroduces the secrets managed identity was meant to remove. Instead: Fix the identity properly.
  • Mistake: Retesting seconds after a role change and concluding it didn't work. Why it is wrong: Propagation takes minutes, and group-based changes can take hours. Instead: Wait, assign directly while debugging, and restart the app to clear cached tokens.
  • Mistake: Assigning roles by hand in the portal during an incident and never recording them. Why it is wrong: The next environment or redeploy misses them, and nobody can review who has access. Instead: Put role assignments in Bicep or Terraform, assign to identities or Entra groups deliberately, and review them in pull requests.
  • Mistake: Allow-listing App Service outbound IPs in firewalls. Why it is wrong: They can change, and they're shared with other tenants. Instead: Use VNet integration with private endpoints.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate fixes the roles and SQL user Why: Checks they can build the passwordless setup correctly from the start
    How to answer

    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:

    • Key Vault: grant Key Vault Secrets User and use AddAzureKeyVault.
    • Blob Storage: grant Storage Blob Data Contributor and create BlobServiceClient with the credential.
    • Azure SQL: 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.

  2. When: Candidate mentions private endpoints or ForbiddenByConnection Why: Checks they understand private endpoints, private DNS and the wider production network design
    How to answer

    I build it in layers:

    • Compute: App Service Premium v3 (or a Container Apps workload-profile environment) in Australia East with zone redundancy, at least two instances, and a health check path.
    • Releases: a staging slot with warm-up and swap (or revisions with traffic splitting).
    • Network: traffic enters through Front Door Premium or Application Gateway with WAF, the app only accepts traffic from it; outbound uses VNet integration, and SQL, Key Vault and Storage are reached through private endpoints with public access off.
    • Identity and ops: managed identity everywhere, Application Insights and alerts on SLOs.
    • Resilience: a warm or cold standby in Australia Southeast with SQL failover groups and geo-redundant storage, all from IaC.

    The trade-off is cost and complexity (private DNS, more resources) versus a much smaller attack surface and a tested recovery path.

  3. When: Candidate mentions EF Core connecting to Azure SQL Why: Checks they can review an EF Core passwordless connection setup
    How to answer

    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.

🛠 Real-world problems: how you handle them

API failed at startup after moving to a new subscription: wrong vault permission model and no SQL user
Situation
We moved an orders API on App Service to a new production subscription in Australia East as part of [a landing zone migration]. It used a user-assigned managed identity for Key Vault and Azure SQL. The cut-over window was [two hours] on a [Sunday night].
Signals
Health checks failed and the app never became ready; startup logs showed `Azure.RequestFailedException: Status: 403 ... ErrorCode: ForbiddenByRbac`. After fixing that, `SqlException 18456: Login failed for user '<token-identified principal>'`.
Investigation
Confirmed the identity was attached and `AZURE_CLIENT_ID` matched it. `az role assignment list --assignee <principalId> --all` showed only *Reader* on the vault. `az keyvault show` showed `enableRbacAuthorization: true`, so the access policy copied from the old vault was ignored. Entra sign-in logs showed tokens issued for SQL, so the SQL failure was the database user, not the network.
Resolution
Immediate: added the *Key Vault Secrets User* role assignment through the Bicep pipeline and created the contained SQL user with read and write roles; restarted the app after a few minutes. Real fix: moved role assignments and a post-deployment SQL script into the same pipeline as the app, so a new environment can't be missing them.
Prevention
A post-deploy smoke test that reads a probe secret and runs `SELECT 1`; Azure Policy requiring RBAC mode on vaults; a migration checklist covering identities, roles, SQL users and private DNS.

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.

↩ Usually asked after

More in Azure

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me