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.
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.
"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 getsdb_datareaderanddb_datawriter, or for sensitive schemas explicitGRANT SELECT, INSERTon specific tables andEXECUTEon specific procedures. It's neverdb_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."
| 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 |
| 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 |
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].
Checks whether the candidate applies least privilege concretely across Azure, SQL and people, and understands why broad roles are dangerous.
Green flags
Red flags
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
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.
| 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 |
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:
GRANT SELECT, INSERT, UPDATE ON SCHEMA::Receipts TO [app-receipts].EXECUTE only, when you want the app unable to run arbitrary DML.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."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):
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.
allowSharedKeyAccess=false.sys.database_role_members and sys.database_permissions in CI or a scheduled job and diff against an expected baseline.az role assignment list --assignee <principalId> --all -o table. Is anything at resource-group or subscription scope?DROP TABLE as that user and read the error.db_owner across your databases and run it on a schedule.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();
listKeys on storage accounts and similar actions, which grant full data access. Instead: Treat Contributor as data owner and disable shared-key access.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.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 |
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.
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.
scp; an app-only token (client credentials or managed identity) carries roles. Authorise on the right one per endpoint.EnableTokenAcquisitionToCallDownstreamApi plus IDownstreamApi, with a distributed token cache across instances.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.
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.
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.
Last updated 23 Nov 2026.