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

📚 Interview question

Show me how a .NET 10 API on Azure reaches Key Vault, Azure SQL and Blob Storage with managed identity and no secrets. Cover DefaultAzureCredential, system versus user-assigned identities, the RBAC roles and SQL users you create, and how developers run the same code locally.

Implementing passwordless access from a .NET 10 app to Key Vault, Azure SQL and Blob Storage with managed identity: Azure.Identity credentials, system vs user-assigned identities, RBAC role assignments in Bicep, contained SQL users, and local development.

Mid-Level Coding Intermediate azure azure-sql devops key-vault managed-identity rbac

🎯 Key points

  • Managed identity gives the app an Entra ID identity with no stored secret
  • DefaultAzureCredential tries environment, workload identity, managed identity, then developer credentials
  • In production prefer ManagedIdentityCredential or restrict the chain
  • User-assigned identity: shared, survives redeploys, needs client id (AZURE_CLIENT_ID)
  • Data-plane roles: Key Vault Secrets User, Storage Blob Data Contributor
  • Azure SQL: CREATE USER FROM EXTERNAL PROVIDER plus db roles; Authentication=Active Directory Default
  • Role assignments in Bicep with guid() names; propagation can take minutes
  • Developers use az login with their own roles on dev resources

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Managed identity is an Entra ID service principal tied to an Azure resource. The platform exposes a local token endpoint, and Azure.Identity asks it for an access token for a specific resource, such as https://vault.azure.net or https://database.windows.net. Nothing secret is stored in my configuration; only resource URIs. There are two kinds. A system-assigned identity lives and dies with the app. A user-assigned identity is a separate resource I can attach to several apps, so role assignments survive redeploys and slot swaps, and I can create it and grant roles before the app exists. With user-assigned I must tell the credential which one to use by client id.

In code I register one credential and pass it to every Azure client. DefaultAzureCredential is convenient because it tries environment variables, workload identity, managed identity and then developer tools like the Azure CLI and Visual Studio, so the same code runs locally and in Azure. In production I prefer to be explicit, with ManagedIdentityCredential or by restricting the chain, because probing credentials that don't exist adds startup latency and can hide misconfiguration. Then I grant data-plane roles on each resource: Key Vault Secrets User on the vault, Storage Blob Data Contributor on the container or account. Azure SQL is different: RBAC doesn't grant database access, so I create a contained user with CREATE USER [app-orders-prod] FROM EXTERNAL PROVIDER and add it to db_datareader and db_datawriter, and the connection string says Authentication=Active Directory Default.

Locally, developers az login and are members of an Entra group that has the same roles on dev resources only. The mistake I see is granting Contributor at the subscription and wondering why reads still fail, or the opposite, granting Owner to make the 403 go away. Least privilege on the exact resource is the whole point."


Roles you actually need

Resource Role or permission Scope
Key Vault (RBAC mode) Key Vault Secrets User The vault
Blob Storage Storage Blob Data Reader or Contributor Container or account
Service Bus Azure Service Bus Data Sender / Receiver Queue, topic or namespace
Azure SQL Contained database user + db_datareader / db_datawriter The database
App Configuration App Configuration Data Reader The store

System vs user-assigned

System-assigned User-assigned
Lifecycle Deleted with the app Independent resource
Shared across apps No Yes
Roles before the app exists No Yes (good for IaC ordering)
Code change None Pass client id (AZURE_CLIENT_ID or ManagedIdentityClientId)

Production example

Moving a payments API from four connection strings and two storage keys to a user-assigned identity removed six secrets from Key Vault and the quarterly rotation runbook. Token acquisition added about 20–50 ms on the first call per resource, then nothing, because the SDK caches tokens and refreshes them before expiry.

🔍 What the interviewer is checking

Checks that the candidate can implement passwordless Azure access end to end, including the parts that are not RBAC.

Green flags

  • Knows DefaultAzureCredential's chain and why to be explicit in production
  • Distinguishes control-plane and data-plane roles
  • Knows Azure SQL needs a contained user from an external provider
  • Has a sensible local development story without production access

Red flags

  • Stores a client secret for a service principal "to make it work"
  • Grants Owner or Contributor to fix 403s
  • Doesn't know how tokens are obtained or cached

📚 Learn in depth

1. How a token is obtained

App code ─▶ ManagedIdentityCredential.GetTokenAsync(scope = "https://vault.azure.net/.default")
          ─▶ local identity endpoint (IDENTITY_ENDPOINT + IDENTITY_HEADER on App Service)
          ─▶ Entra ID issues a JWT (aud = vault, oid = identity's object id)
App code ─▶ Key Vault: GET /secrets/Db-Password  Authorization: Bearer <JWT>
Key Vault ─▶ checks RBAC assignments for that oid at that scope ─▶ 200 or 403

The identity endpoint is only reachable from inside the resource, which is why nothing secret has to be configured. Tokens last around an hour or more; the SDK caches them per scope and refreshes them early.

2. The DefaultAzureCredential chain

EnvironmentCredential → WorkloadIdentityCredential → ManagedIdentityCredential
→ VisualStudioCredential → AzureCliCredential → AzurePowerShellCredential
→ AzureDeveloperCliCredential → (interactive browser, off by default)

The first credential that returns a token wins. That makes local and cloud code identical, but it has costs: probing can add seconds at startup, and a developer credential may silently win where you expected managed identity. Options: use ManagedIdentityCredential in production and DefaultAzureCredential only in development, set Exclude* options, or use the AZURE_TOKEN_CREDENTIALS environment variable supported by recent Azure.Identity versions to limit the chain to development or production credentials.

3. Azure SQL is not RBAC

Azure RBAC controls the server resource (control plane). Database access is SQL permissions. You set an Entra admin on the server, connect as that admin, and run:

CREATE USER [id-orders-api-prod] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [id-orders-api-prod];
ALTER ROLE db_datawriter ADD MEMBER [id-orders-api-prod];

Microsoft.Data.SqlClient gets the token itself when the connection string has Authentication=Active Directory Default (or Active Directory Managed Identity with User Id=<client id> for a user-assigned identity). Turning on Entra-only authentication on the server then removes SQL logins and passwords entirely.

4. Propagation and caching

New role assignments usually apply within a few minutes, but can take up to about 10. Changes made through group membership for a managed identity can take hours, because the identity's tokens are cached by the platform. In IaC, create role assignments before the app's first deployment, or use a user-assigned identity created in an earlier step.

5. Local development

Developers sign in with az login (or Visual Studio). Put developers in an Entra group, for example grp-orders-developers, with data roles on dev resources only. Production stays reachable only by the production identity. For local emulators (Azurite, SQL in a container), use connection strings in user secrets and switch by environment.

Try it yourself

  1. Enable a system-assigned identity on an App Service and call ManagedIdentityCredential.GetTokenAsync; decode the token at jwt.ms and find oid and aud.
  2. Read a Key Vault secret before and after assigning Key Vault Secrets User; time how long the role takes to apply.
  3. Create a contained SQL user for the identity and connect with Authentication=Active Directory Default.
  4. Run the app locally with az login and with AZURE_TOKEN_CREDENTIALS=prod to see the chain change.

💻 Code

Program.cs for passwordless access to Key Vault, Blob Storage and Azure SQL (EF Core), then the Bicep that grants the roles.

using Azure.Core;
using Azure.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Azure;

var builder = WebApplication.CreateBuilder(args);

// Explicit in Azure, convenient locally. A user-assigned identity needs its client id.
TokenCredential credential = builder.Environment.IsDevelopment()
    ? new DefaultAzureCredential()
    : new ManagedIdentityCredential(
        ManagedIdentityId.FromUserAssignedClientId(builder.Configuration["AZURE_CLIENT_ID"]!));

// Key Vault secrets as configuration, e.g. a third-party API key with no Entra support.
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration["KeyVault:Uri"]!), credential);

builder.Services.AddAzureClients(c =>
{
    c.AddBlobServiceClient(new Uri(builder.Configuration["Storage:BlobUri"]!));
    c.UseCredential(credential);
});

// No password: SqlClient gets an Entra token for database.windows.net.
// Connection string: Server=tcp:sql-orders-prod-aue.database.windows.net,1433;Database=orders;
//   Authentication=Active Directory Default;Encrypt=True;
builder.Services.AddDbContext<OrdersDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));

var app = builder.Build();
app.MapGet("/healthz", () => Results.Ok());
app.Run();

public sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options) : DbContext(options);
param location string = 'australiaeast'

resource identity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = {
  name: 'id-orders-api-prod'
  location: location
}

resource vault 'Microsoft.KeyVault/vaults@2023-07-01' existing = { name: 'kv-orders-prod-aue' }
resource storage 'Microsoft.Storage/storageAccounts@2023-05-01' existing = { name: 'stordersprodaue' }

// Built-in role ids
var keyVaultSecretsUser = '4633458b-17de-408a-b874-0445c86b69e6'
var storageBlobDataContributor = 'ba92f5b4-2d11-453d-a403-e96b0029c9fe'

resource kvRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(vault.id, identity.id, keyVaultSecretsUser) // deterministic: re-deploys are idempotent
  scope: vault
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', keyVaultSecretsUser)
    principalId: identity.properties.principalId
    principalType: 'ServicePrincipal'
  }
}

resource blobRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(storage.id, identity.id, storageBlobDataContributor)
  scope: storage
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', storageBlobDataContributor)
    principalId: identity.properties.principalId
    principalType: 'ServicePrincipal'
  }
}
-- Run once as the server's Entra admin, in the orders database.
CREATE USER [id-orders-api-prod] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [id-orders-api-prod];
ALTER ROLE db_datawriter ADD MEMBER [id-orders-api-prod];

⚠ Common mistakes

  • Mistake: Granting Contributor or Owner and expecting data access. Why it is wrong: Those are control-plane roles; reading secrets or blobs needs data-plane roles, and Owner is far too much privilege. Instead: Grant Key Vault Secrets User or Storage Blob Data Contributor on the specific resource.
  • Mistake: Expecting an Azure RBAC role to give SQL database access. Why it is wrong: Database permissions are SQL users and roles, unlike on-premises SQL Server with Windows logins. Instead: CREATE USER ... FROM EXTERNAL PROVIDER and add it to the right database roles.
  • Mistake: Using a user-assigned identity without telling the credential which one. Why it is wrong: With several identities attached, the token request fails or uses the wrong one. Instead: Set AZURE_CLIENT_ID or ManagedIdentityClientId.
  • Mistake: Sharing one user-assigned identity across many unrelated apps to save effort. Why it is wrong: Every app gets the union of all permissions, an audit log entry can't tell you which app acted, and removing access for one app affects all of them. Instead: One identity per app (or per tightly related group), each with its own role assignments, created and deleted through IaC.
  • Mistake: Relying on the full DefaultAzureCredential chain in production. Why it is wrong: It probes credentials that don't exist, slows startup and can mask a missing identity. Instead: Use ManagedIdentityCredential in Azure or restrict the chain.
  • Mistake: Creating a new credential per request. Why it is wrong: Each instance has its own token cache, so you request tokens constantly and can be throttled. Instead: Create one credential and share it through DI.
  • Mistake: Giving developers roles on production resources so local debugging works. Why it is wrong: It breaks least privilege and audit trails. Instead: Developers get roles on dev resources through an Entra group, or use emulators (Azurite, the SQL Server container, the Service Bus emulator) with local connection strings.
  • Mistake: Deploying the app and its role assignment in the same step, then failing the first health check. Why it is wrong: Role propagation can take minutes, and group membership changes for a managed identity can take hours. Instead: Create the identity and roles first, or retry Key Vault loading at startup with a short back-off.
  • Mistake: Hard-coding connection string keywords from an old blog post. Why it is wrong: SqlClient's Entra authentication options have changed across versions. Instead: Use a current Microsoft.Data.SqlClient and check its documented Authentication values.

🏛 Senior insight: trade-offs

The win is not only no secrets; it is that access becomes reviewable. Every permission is a role assignment in Bicep that shows up in a pull request, and Entra sign-in logs show which identity touched which resource. For the few services without Entra support (some third-party APIs), Key Vault stays, read through the same identity.

Option When it fits Cost When not to
System-assigned identity One app, simple lifecycle Free, zero config Roles must exist before deploy; shared access
User-assigned identity Several apps, IaC ordering, slots One more resource to manage Tiny single app
Workload identity federation AKS pods, GitHub Actions Federated credential setup Code running on App Service (use managed identity)
Key Vault secret Third-party system without Entra Rotation work Azure services that support Entra auth

I measure success by the number of secrets in Key Vault going down and by Entra sign-in logs showing only managed identities hitting production data.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Authentication=Active Directory Default for SQL Why: Checks they can review an EF Core and Azure SQL passwordless setup in detail
    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.

  2. When: Candidate loads Key Vault secrets into configuration Why: Checks they handle secret rotation, caching, refresh and start-up failures
    How to answer

    I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.

    For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.

    The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.

  3. When: Candidate lists the Azure services the identity reaches Why: Checks they know what each service is for and where the app's data lives
    How to answer

    A typical .NET team uses a small, repeatable set of Azure services:

    • Compute: App Service for web apps and APIs, Azure Functions for event-driven code, Container Apps or AKS for containers.
    • Data: Azure SQL Database for relational data, Blob Storage for files, and Azure Managed Redis (the successor to Azure Cache for Redis) for caching.
    • Platform: Key Vault for secrets and certificates, App Configuration for settings and feature flags, Service Bus for messaging, Application Insights (on Azure Monitor) for telemetry.

    Everything is wired together with managed identity and Entra ID RBAC, not connection strings, and deployed with infrastructure as code. The trade-off: managed PaaS services remove patching and plumbing, but you accept each service's limits, pricing model and region availability.

🛠 Real-world problems: how you handle them

Removing every secret from a payments API before an Essential Eight audit
Situation
A payments API on App Service in Australia East held [four] SQL and Storage connection strings in app settings and [two] storage keys in Key Vault. An upcoming [ACSC Essential Eight / internal security] review flagged long-lived shared secrets, and one key had already been found in a [support ticket].
Signals
Security scan flagged secrets in app settings; Key Vault had secrets with no expiry; Storage account metrics showed access with account keys from [two unknown IP addresses] in the last month.
Investigation
Listed all settings with `az webapp config appsettings list` and every Key Vault secret's consumers. Checked Storage diagnostic logs in Log Analytics (KQL on `StorageBlobLogs`, `AuthenticationType`) to find who used account keys. Confirmed the SQL server already had an Entra admin.
Resolution
Immediate: rotated the storage keys that had leaked. Real fix: created a user-assigned identity in Bicep with *Storage Blob Data Contributor* and *Key Vault Secrets User*, created a contained SQL user, switched SqlClient to `Authentication=Active Directory Default` and the SDK clients to the shared credential, deployed through a staging slot, then disabled shared key access on the storage account and turned on Entra-only authentication for SQL.
Prevention
Azure Policy denying storage accounts with shared key access and SQL servers without Entra-only authentication; a pipeline check that fails on connection strings containing `Password=` or `AccountKey=`; role assignments reviewed in pull requests.

How to tell it (STAR)

**S:** Our payments API had [four] connection strings and [two] storage keys, and one key had turned up in a support ticket just before a security review. **T:** I owned removing shared secrets without downtime. **A:** I created a user-assigned identity in Bicep with data roles on Key Vault and Storage, added a contained SQL user, and switched the code to one shared `TokenCredential`. We released through a staging slot, then disabled shared key access and SQL password logins. **R:** Six secrets and the quarterly rotation runbook disappeared, the review passed that control, and the storage logs showed [zero] key-based access afterwards.

↩ Usually asked after

More in Azure

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me