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

📚 Interview question

How do you apply least privilege to a .NET service running in Azure with an Azure SQL database? Cover managed identities and RBAC scopes, database roles and permissions, just-in-time admin access with PIM, and what the ACSC Essential Eight expects for administrative privileges.

Least privilege end to end: one managed identity per workload, narrow RBAC roles at the smallest scope, contained database users with only the grants they need, separate migration identities, PIM for humans, and the Essential Eight 'restrict administrative privileges' strategy.

Mid-Level Theory Intermediate azure-rbac essential-eight least-privilege managed-identity security sql-server

🎯 Key points

  • One identity per workload: system-assigned for a single resource; user-assigned when several instances of the same app need one identity (slots, scale sets, pre-created DB users) - sharing a user-assigned identity across unrelated apps merges their permissions
  • Data-plane roles at the smallest scope: Storage Blob Data Reader on one container, Key Vault Secrets User on one vault, Service Bus Data Sender on one queue; Contributor includes actions like listKeys that grant full data access
  • Contained database user FROM EXTERNAL PROVIDER with db_datareader/db_datawriter or object-level GRANT, never db_owner (which can alter schema, permissions and, with ownership chaining or TRUSTWORTHY, reach beyond the database); schema changes run under a separate migration identity
  • Network least privilege too: private endpoints, public network access disabled, SQL firewall rules limited to what's needed, Entra-only authentication
  • Separate runtime and deployment identities: the pipeline deploys, the app only reads and writes data
  • Humans: no standing admin; Entra PIM for just-in-time, time-bound, approved and audited elevation; separate privileged accounts
  • Essential Eight 'restrict administrative privileges': validated requests, regular revalidation, no internet or email from privileged accounts, JIT admin and logging of privileged actions at higher maturity levels
  • Verify and monitor: Activity Log alerts on role assignment writes, PIM activation logs, SQL auditing of permission changes, Azure Policy, access reviews, Defender for Cloud

⏱ 30-second answer

Least privilege means every identity gets only the permissions it needs, at the smallest scope, for the shortest time. For a .NET service in Azure I give each workload its own managed identity and assign data-plane roles at resource scope: Storage Blob Data Reader on one container, Key Vault Secrets User on one vault, never Contributor on the subscription. In Azure SQL the app is a contained user with read/write or object-level grants, not db_owner; migrations run under a separate identity in the pipeline. Humans have no standing admin rights: they elevate through Entra PIM, time-bound and audited. That maps to the Essential Eight's restrict administrative privileges strategy. The trade-off is operational friction: narrow scopes mean more role assignments and more "access denied" during development, so you codify them in Bicep or Terraform rather than clicking in the portal.

🗣 Full answer (senior)

How I would answer this in an interview

"Least privilege is about limiting the blast radius when something is compromised. I think about it in three dimensions: what an identity can do, where - the scope - and for how long. For a .NET service in Azure, the workload gets its own managed identity. I assign data-plane roles, not management-plane ones: if the API reads receipts from one container it gets Storage Blob Data Reader on that container, not Storage Account Contributor, which would let it list keys and effectively become admin. Key Vault Secrets User on its own vault. Service Bus Data Sender on one queue. Those assignments live in Bicep next to the app, so they're reviewed like code.

In the database the identity becomes a contained user created FROM EXTERNAL PROVIDER. It gets db_datareader and db_datawriter, or for sensitive schemas explicit GRANT SELECT, INSERT on specific tables and EXECUTE on specific procedures. It's never db_owner, because then a SQL injection bug can drop tables or read the audit schema. EF Core migrations run from the pipeline under a separate migration identity with DDL rights, so the running app can't change its own schema. People get the same treatment: no standing Owner on production, they activate a role through Privileged Identity Management for a few hours with a justification and sometimes approval, and every activation is audited.

The mistake I see is the app identity with Contributor on the resource group 'because it was easier'. That turns any remote code execution bug into full control of the environment. The Essential Eight lists restricting administrative privileges as one of its eight strategies, and at higher maturity levels it expects just-in-time admin and privileged accounts that can't browse the web or read email. Least privilege isn't a setting; it's a habit of asking 'what's the smallest scope that works?' every time you write a role assignment."


Roles: what the app usually needs versus what it often gets

Resource Right-sized role Over-privileged role often seen Why it matters
Blob Storage Storage Blob Data Reader / Contributor on a container Storage Account Contributor Contributor can list account keys -> full data access
Key Vault Key Vault Secrets User on one vault Key Vault Administrator / access policy "all" Can read every secret, delete keys
Service Bus Azure Service Bus Data Sender / Receiver on an entity Azure Service Bus Data Owner on the namespace Can manage entities and read every queue
Azure SQL Contained user, db_datareader/db_datawriter or object GRANTs db_owner / server admin SQL injection becomes schema destruction
Resource group None for the runtime identity Contributor RCE in the app becomes control of the environment

Identities by purpose

Identity Permissions Lifetime
App runtime (managed identity) Data-plane roles on its own resources Lives with the app
Deployment pipeline (workload identity federation) Contributor on the app's resource group, no data-plane read Per pipeline run token
Migration identity DDL on the database (db_ddladmin or specific grants) Used only in the release stage
Engineer Reader by default; PIM-eligible for Contributor/Owner Hours, on activation
Break-glass Global admin, excluded from Conditional Access lock-out Sealed, monitored, tested quarterly

Production example

An access review of [a payments platform] found [14 of 22] workload identities holding Contributor at resource-group scope. Replacing them with data-plane roles took [two sprints] of Bicep changes. A later pen test achieved code execution in [one internal service] through a vulnerable dependency; with the narrowed identity, the tester could read only that service's one queue instead of the whole environment, and the finding was rated [medium instead of critical].

🔍 What the interviewer is checking

Checks whether the candidate applies least privilege concretely across Azure, SQL and people, and understands why broad roles are dangerous.

Green flags

  • Distinguishes control-plane and data-plane roles and knows Contributor can list keys.
  • One identity per workload, roles at the smallest scope, in IaC.
  • Runtime database user without DDL; separate migration identity.
  • PIM and the Essential Eight admin privilege strategy for humans.
  • Talks about verifying and reviewing, not just configuring once.

Red flags

  • "The app runs as db_owner" or Contributor without concern.
  • Treats least privilege only as a database topic.
  • Standing admin rights as normal.

📚 Learn in depth

1. Why least privilege limits damage

Attacks chain: a foothold (vulnerable package, injection, stolen token) is followed by lateral movement and privilege escalation. Every permission an identity holds is something the attacker inherits. Least privilege doesn't stop the foothold; it shrinks what it's worth.

  RCE in Receipts API
        |
        v
  identity: mi-receipts
        |
   +----+----------------------------+
   | Over-privileged                 | Least privilege
   | Contributor on rg-prod          | Blob Data Reader on /receipts
   | -> list storage keys            | -> read receipts container only
   | -> read Key Vault via policy    | -> nothing else
   | -> redeploy other apps          |
   v                                 v
  whole environment               one container

2. Azure RBAC: control plane versus data plane

  • Control plane (Azure Resource Manager): create, configure, delete resources. Roles like Owner, Contributor, Reader, and service-specific contributors.
  • Data plane: read and write the data inside. Roles like Storage Blob Data Contributor, Key Vault Secrets User, Service Bus Data Receiver, Cosmos DB Built-in Data Contributor.
  • Some control-plane actions reach the data anyway: Microsoft.Storage/storageAccounts/listKeys/action is in Contributor, which is why Contributor is effectively data owner unless you disable shared-key access.

Scope hierarchy: management group > subscription > resource group > resource > (for some services) sub-resource such as a blob container or queue. Assign at the lowest scope that works. Role assignments inherit downwards, so one assignment at subscription scope can quietly grant access to everything created later.

3. System-assigned versus user-assigned managed identity

System-assigned User-assigned
Lifecycle Tied to one resource Independent resource
Sharing One resource only Several resources can use it
Fits One app, one identity Blue-green slots, scale sets, pre-provisioned DB users
Risk None extra Sharing across unrelated apps defeats least privilege

4. Database least privilege in Azure SQL

 Server level:  Entra admin group (PIM-managed), Entra-only auth on
 Database:
   app-receipts      -> db_datareader, db_datawriter  (or GRANTs per schema)
   app-reporting     -> SELECT on reporting schema only
   mig-receipts      -> db_ddladmin (pipeline release stage only)
   support-readonly  -> SELECT on views that mask PII

Techniques:

  • Schema-level grants: GRANT SELECT, INSERT, UPDATE ON SCHEMA::Receipts TO [app-receipts].
  • Procedures with EXECUTE only, when you want the app unable to run arbitrary DML.
  • Row-level security to restrict rows by tenant or user, enforced by the engine.
  • Dynamic data masking for support roles (not a security boundary on its own; users with ad-hoc query rights can infer masked values).
  • Separate migration identity: Database.Migrate() at app start-up forces the runtime identity to hold DDL rights, which is a good reason to run migrations from the pipeline with bundles or scripts.

5. People: PIM and Conditional Access

  • Entra PIM makes users eligible for a role; they activate it for 1-8 hours with justification, optional approval and MFA. Activations are logged and can trigger alerts.
  • Access reviews periodically ask owners to confirm who still needs what.
  • Conditional Access: require phishing-resistant MFA and compliant devices for admin roles.
  • Separate privileged accounts for admin work; no email or web browsing with them.
  • Break-glass accounts: two cloud-only accounts, excluded from Conditional Access, credentials sealed, sign-ins alerted.

6. The Essential Eight on administrative privileges

"Restrict administrative privileges" is one of the eight strategies, assessed at Maturity Levels One to Three. In broad terms (check the current ACSC publication for exact wording):

  • Requests for privileged access are validated when first requested and revalidated regularly; access is removed after a period of inactivity.
  • Privileged accounts can't access the internet, email and web services.
  • Privileged users use separate privileged and unprivileged environments.
  • At higher levels, just-in-time administration, privileged access limited to what duties require, and logging and monitoring of privileged access and changes.

PIM, Conditional Access and dedicated admin workstations are the usual Azure implementations. For government systems, the ISM has matching controls and IRAP assessors will ask for evidence.

7. Verifying it stays true

  • Azure Policy: deny Owner/Contributor assignments to managed identities, require allowSharedKeyAccess=false.
  • Defender for Cloud recommendations flag overly permissive identities.
  • Entra permissions management or simple Resource Graph queries list role assignments by principal.
  • SQL: query sys.database_role_members and sys.database_permissions in CI or a scheduled job and diff against an expected baseline.

Try it yourself

  1. List all role assignments for one of your app's identities: az role assignment list --assignee <principalId> --all -o table. Is anything at resource-group or subscription scope?
  2. Replace a Contributor assignment with a data-plane role in Bicep and redeploy; confirm the app still works.
  3. Create a contained user for a managed identity and grant only schema-level permissions; try a DROP TABLE as that user and read the error.
  4. Make yourself PIM-eligible (not active) for Contributor on a dev subscription and practise activation.
  5. Write a SQL query that lists every member of db_owner across your databases and run it on a schedule.

💻 Code

Bicep: a user-assigned identity for the API with data-plane roles scoped to one container and one vault:

param location string = resourceGroup().location

resource apiIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = {
  name: 'mi-receipts-api-prod'
  location: location
}

resource storage 'Microsoft.Storage/storageAccounts@2023-05-01' existing = {
  name: 'streceiptsprod'
}

resource container 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-05-01' existing = {
  name: '${storage.name}/default/receipts'
}

// Storage Blob Data Contributor, scoped to ONE container, not the account or resource group.
resource blobRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(container.id, apiIdentity.id, 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')
  scope: container
  properties: {
    principalId: apiIdentity.properties.principalId
    principalType: 'ServicePrincipal'
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')
  }
}

SQL: the runtime identity can read and write one schema; only the migration identity can change the schema:

CREATE USER [mi-receipts-api-prod] FROM EXTERNAL PROVIDER;
GRANT SELECT, INSERT, UPDATE ON SCHEMA::Receipts TO [mi-receipts-api-prod];
-- No DELETE: the app soft-deletes. No DDL: migrations run elsewhere.

CREATE USER [mi-receipts-migrations] FROM EXTERNAL PROVIDER;
ALTER ROLE db_ddladmin ADD MEMBER [mi-receipts-migrations];

-- Baseline check for CI or a scheduled job: nobody unexpected in db_owner.
SELECT r.name AS role_name, m.name AS member_name
FROM sys.database_role_members AS drm
JOIN sys.database_principals AS r ON r.principal_id = drm.role_principal_id
JOIN sys.database_principals AS m ON m.principal_id = drm.member_principal_id
WHERE r.name = 'db_owner';

The .NET side uses the specific identity rather than probing for credentials:

using Azure.Identity;
using Azure.Storage.Blobs;

var builder = WebApplication.CreateBuilder(args);

var credential = new ManagedIdentityCredential(
    ManagedIdentityId.FromUserAssignedClientId(builder.Configuration["Identity:ClientId"]!));

// The client is scoped to the one container the identity can access.
builder.Services.AddSingleton(new BlobContainerClient(
    new Uri(builder.Configuration["Storage:ReceiptsContainerUri"]!), credential));

var app = builder.Build();
app.Run();

⚠ Common mistakes

  • Mistake: Giving the app's identity Contributor on the resource group. Why it is wrong: Any code execution bug becomes control of every resource in the group, including listing storage keys and redeploying other apps. Instead: Assign data-plane roles on the specific resources the app uses.
  • Mistake: Assuming Contributor can't read data. Why it is wrong: Contributor includes listKeys on storage accounts and similar actions, which grant full data access. Instead: Treat Contributor as data owner and disable shared-key access.
  • Mistake: Making the app's database user db_owner so EF Core migrations work at start-up. Why it is wrong: SQL injection or RCE can drop tables, read audit data or grant itself more access. Instead: Run migrations from the pipeline under a separate identity and give the runtime user only DML.
  • Mistake: Sharing one user-assigned identity across unrelated apps. Why it is wrong: Each app inherits every other app's permissions. Instead: One identity per workload; share only across instances of the same app.
  • Mistake: Standing Owner rights for senior engineers. Why it is wrong: A phished engineer account becomes tenant-wide compromise, and Essential Eight maturity can't be met. Instead: PIM-eligible roles activated just in time, with MFA and justification.
  • Mistake: Assigning roles at subscription scope for convenience. Why it is wrong: Assignments inherit to every resource created later, silently widening access. Instead: Assign at resource or sub-resource scope in IaC.
  • Mistake: Treating dynamic data masking as access control. Why it is wrong: Users with query rights can infer masked values with predicates. Instead: Use permissions, views and row-level security; masking is a convenience layer.
  • Mistake: Never reviewing permissions after go-live. Why it is wrong: Temporary grants for debugging become permanent. Instead: Access reviews, Azure Policy and scheduled permission baselines.

🏛 Senior insight: trade-offs

Least privilege fails mostly through convenience drift: a temporary Contributor grant during an incident, a shared identity to save a ticket, db_owner because migrations run at start-up. The senior move is to make the narrow path the easy path: role assignments in Bicep or Terraform modules with sensible defaults, a migration pipeline so the app never needs DDL, PIM so nobody needs standing access, and Azure Policy that denies the broad assignments outright.

Identity is only one axis. Network least privilege limits who can even attempt to authenticate: Azure SQL with public network access disabled and a private endpoint, or firewall rules limited to known egress, and Entra-only authentication so there are no SQL logins to brute-force. Monitoring proves it stays true: send the Activity Log to Log Analytics and alert on Microsoft.Authorization/roleAssignments/write, review PIM activation history, and audit GRANT/ALTER ROLE statements in SQL auditing. An unexpected role assignment is often the first visible sign of an attacker establishing persistence.

Know the trade-off: very fine-grained permissions (per-table GRANTs, per-queue roles) cost maintenance and slow developers. Match granularity to data sensitivity. Measure with the count of privileged assignments per identity, standing admin accounts, and time-to-revoke after someone leaves.

Control When it fits Cost When not to
Data-plane RBAC at resource scope Every Azure workload More assignments to manage Never skip
Object-level SQL GRANTs Sensitive schemas, shared databases Grants to maintain per migration Small single-app databases with no PII (schema-level is enough)
Private endpoint + public access disabled Production data stores DNS and networking complexity Throwaway dev resources
PIM just-in-time All human admin access Activation friction Break-glass accounts

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions managed identities or Key Vault access. Why: Checks the link between removing secrets with managed identity and scoping that identity's permissions.
    How to answer

    A secret is anything that grants access or proves identity: database passwords, API keys and tokens, client secrets, JWT signing keys, SAS tokens. The best secret is no secret at all: in Azure I use managed identity so the app authenticates to Azure SQL, Storage and Service Bus with Entra tokens, not stored credentials. What must remain a secret, typically a third-party API key that doesn't support Entra, goes in Azure Key Vault, read through the AddAzureKeyVault configuration provider using the app's managed identity, with Key Vault RBAC per app and a vault per environment. Locally, developers use dotnet user-secrets or their own Entra sign-in against a dev vault. Nothing goes in appsettings.json or the repo, and secret scanning blocks pushes. The trade-off: Entra and Key Vault become runtime dependencies with network hops and throttling limits, so you load at start-up, cache and reload on an interval, and automate rotation rather than doing it by hand.

  2. When: Candidate mentions one service calling another with its managed identity. Why: Checks least privilege for service-to-service calls into your own APIs using app roles.
    How to answer

    Register the API in Entra ID with an App ID URI, delegated scopes (Orders.Read) for user calls and app roles (Orders.Read.All) for application calls. Register each client separately and grant it those permissions. In the API, AddMicrosoftIdentityWebApi (Microsoft.Identity.Web) wires up JWT bearer validation against your tenant.

    • A user token carries scp; an app-only token (client credentials or managed identity) carries roles. Authorise on the right one per endpoint.
    • To call a downstream API as the user, use on-behalf-of: EnableTokenAcquisitionToCallDownstreamApi plus IDownstreamApi, with a distributed token cache across instances.
    • A managed identity caller requests api://<app-id>/.default; you assign it an app role.

    The trade-off: Entra does the heavy lifting, but permissions and consent live in the portal, so manage them as code.

  3. When: Candidate says the runtime identity should not have DDL rights. Why: Checks the candidate connects deployment design to database permissions.
    How to answer

    Database.Migrate() at start-up means the runtime identity must hold DDL rights, so any SQL injection or RCE can alter or drop schema. It also couples deployment to start-up: several scaled-out instances can try to migrate at once (EF Core 9+ takes a database lock to serialise this, but a long migration still blocks start-up and health checks), and a failed migration takes the app down with it. Instead I generate an idempotent script or a migration bundle (dotnet ef migrations bundle) in CI and run it once in the release stage under a separate migration identity with db_ddladmin, after a backup and an approval gate for production. Migrations are written to be backward compatible (expand, then contract) so the old and new app versions both work during rollout, and the runtime identity keeps only DML.

🛠 Real-world problems: how you handle them

Pen-test RCE contained by a narrowly scoped managed identity
Situation
[A payments platform] with [~20] .NET services on Azure Container Apps and Azure SQL. An access review six months earlier had replaced resource-group Contributor assignments with data-plane roles. An annual external pen test was under way.
Signals
The pen-test report showed remote code execution in an internal notification service through a vulnerable image-processing dependency; the testers then tried to pivot using the container's managed identity token.
Investigation
Reviewed the testers' evidence and Entra sign-in logs for the identity's token requests, then listed its role assignments with `az role assignment list --assignee`. It held only Azure Service Bus Data Receiver on one queue and Key Vault Secrets User on its own vault. SQL audit showed no logins from that identity, because it had no database user.
Resolution
Immediate: patched the dependency and redeployed the service. Long term: added Azure Policy denying Owner and Contributor assignments to managed identities, and moved the last two services running migrations at start-up to a pipeline migration identity.
Prevention
Quarterly Entra access reviews, a Resource Graph query in CI that fails if any workload identity has a role at resource-group scope or higher, a db_owner baseline check, and PIM for all human admin roles.

How to tell it (STAR)

**S:** We ran [around 20] .NET services in Azure, and an access review showed most workload identities had Contributor on their resource groups. **T:** I [led] the work to bring them down to least privilege without breaking deployments. **A:** I replaced the broad roles with data-plane roles at resource scope in our Bicep modules, moved migrations to a pipeline identity so apps had no DDL rights, and put engineers on PIM. **R:** When a pen tester later got code execution in one service, they could only read [one queue]; the finding was rated [medium rather than critical], and we now have a policy that blocks broad assignments automatically.

↩ Usually asked after

More in Senior Security Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me