Azure from the administrator’s side
RBAC and custom roles, app registrations and service principals, managed identities including servers with Azure Arc, and Key Vault with roles, a firewall and an audit log. Permissions, credentials and secrets in Azure without keys in configuration.
A service account with the Contributor role on an entire subscription has more permissions than it needs, yet it cannot read a secret from Key Vault. An API key in a configuration file works until it leaks or has to be changed, and an application’s client secret expires after two years when nobody knows who owns the application. This document covers four related parts of Azure administration: RBAC with custom roles, app registrations and service principals, managed identities (including on-premises servers with Azure Arc) and Azure Key Vault.
RBAC and custom roles
Principal, role and scope
A role assignment joins a principal (a user, group, service principal or managed identity), a role definition and a scope: a management group, subscription, resource group or single resource. An assignment at a higher level applies to everything below it. Entra ID roles are a separate permission system and are not covered by this model.
Permissions from multiple assignments add up. There is no ordering or priority, and access blocked in one role is opened by another, so permissions are assigned at the lowest practical scope. Roles are assigned to groups, not individuals, also because of limits: 5000 assignments per subscription, 500 per management group and 5000 custom roles per tenant. Managed identities are the exception: roles are assigned to them directly, because tokens are cached (see the section on managed identities).
Actions and DataActions
A role definition has four permission lists. Actions and NotActions cover the management plane, that is Azure Resource Manager calls: creating, changing and deleting resources and reading their configuration. DataActions and NotDataActions cover the data plane: reading a blob, a queue message or a secret value. A role with an asterisk in Actions does not gain access to data as a result.
A permission string has the form Provider/resourceType/operation, and the ending indicates the kind of call: read is GET, write is PUT or PATCH, delete is DELETE, and action covers custom operations such as restarting a machine. The effective result of a role is Actions minus NotActions and DataActions minus NotDataActions. NotActions is not a deny: if one role excludes an operation and another role allows it, the principal can perform it. A true deny is a deny assignment, but Azure creates those itself and customer-managed assignments cannot be created (the feature is in private preview, as of October 2026). Restricting permissions therefore comes down to granting less.
The effect is visible in built-in roles. Contributor is * in Actions minus, among others, Microsoft.Authorization/*/Write and Microsoft.Authorization/*/Delete, so it manages everything except access, and its DataActions are empty. Data is read only by a role with DataActions, such as Storage Blob Data Reader or Key Vault Secrets User (Microsoft.KeyVault/vaults/secrets/getSecret/action, valid only for vaults in the RBAC model). There is a workaround: whoever manages a storage account can retrieve its keys and read data with them, as long as the account allows key access.
Built-in roles and delegation
A custom role is created only when a built-in role, assigned to a group and narrowed by scope, is not enough. Data roles are covered in the sections on Key Vault and managed identities. Management and delegation roles:
| Need | Built-in role | Scope |
|---|---|---|
| A team manages an application’s resources | Contributor | the application’s resource group, group GG-Azure-Portal-Contributors |
| Read-only view | Reader | subscription, group GG-Azure-Readers |
| Granting access to others | Role Based Access Control Administrator | resource group, with a condition |
| Full control including access | Owner | exceptionally, at the narrowest possible scope |
For delegation, Role Based Access Control Administrator is a better choice than User Access Administrator (a broad Microsoft.Authorization/* set): it has only creating and deleting assignments, read access and Microsoft.Support/* (support requests). It is assigned with a condition that limits which roles may be granted; without a condition such an administrator can grant any role, including Owner. The condition covers writing and deleting an assignment separately, and the list of permitted roles appears in it twice: for the role in the request (@Request) and for the role of the existing assignment (@Resource).
$scope = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-portal-prod-weu'
$roles = '{<role-id-1>, <role-id-2>}' # roles the delegate may grant and remove
$condition = "((!(ActionMatches{'Microsoft.Authorization/roleAssignments/write'})) OR " +
"(@Request[Microsoft.Authorization/roleAssignments:RoleDefinitionId] ForAnyOfAnyValues:GuidEquals $roles)) AND " +
"((!(ActionMatches{'Microsoft.Authorization/roleAssignments/delete'})) OR " +
"(@Resource[Microsoft.Authorization/roleAssignments:RoleDefinitionId] ForAnyOfAnyValues:GuidEquals $roles))"
New-AzRoleAssignment -ObjectId '<delegate-object-id>' -Scope $scope `
-RoleDefinitionId 'f58310d9-a9f6-439a-9e8d-f62e7b41a168' `
-Condition $condition -ConditionVersion '2.0'
The syntax comes from the role delegation examples (the “Constrain roles” example). A known limitation: a custom role with a condition cannot be delegated through Privileged Identity Management.
Custom role
A custom role is created when no built-in role fits: it grants too much or too little. The definition is JSON with four permission lists and assignableScopes, the scopes where the role may be assigned. The rules that matter in practice:
assignableScopescannot contain/or an asterisk; it names one management group, subscriptions or resource groups.- A role with
dataActionscannot be assigned at management group scope, but it can list that scope inassignableScopesand be assigned on the subscriptions within it. - Only one asterisk is allowed in a single permission string; the documentation recommends listing operations explicitly.
- A role is created with
Microsoft.Authorization/roleDefinitions/writeon the scopes inassignableScopes; of the built-in roles, Owner and User Access Administrator have it. - A role is identified by a GUID that does not change when the role is renamed. Scripts use the GUID.
A missing operation is found with Get-AzProviderOperation and a pattern, for example Get-AzProviderOperation Microsoft.Compute/virtualMachines/*; data plane operations carry the isDataAction flag.
Example: a virtual machine operator for one resource group starts, restarts and stops (with deallocation) machines and reads their state, without the right to change size, disks or networking. The built-in Virtual Machine Contributor role grants far more (creating and deleting machines, configuration changes), so a custom role is created with six management plane operations. Reading the resource group is needed for the portal and cmdlets to list the machines; instanceView/read provides the power state. Stopping without deallocation (powerOff/action) is deliberately left out of the role, because the machine still incurs cost.
{
"name": "11111111-2222-3333-4444-555555555555",
"properties": {
"roleName": "VM Operator",
"description": "Start, restart and stop with deallocation of virtual machines, and read their state.",
"type": "CustomRole",
"permissions": [
{
"actions": [
"Microsoft.Resources/subscriptions/resourceGroups/read",
"Microsoft.Compute/virtualMachines/read",
"Microsoft.Compute/virtualMachines/instanceView/read",
"Microsoft.Compute/virtualMachines/start/action",
"Microsoft.Compute/virtualMachines/restart/action",
"Microsoft.Compute/virtualMachines/deallocate/action"
],
"notActions": [],
"dataActions": [],
"notDataActions": []
}
],
"assignableScopes": [
"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-portal-prod-weu"
]
}
}
The role is created with a PUT call to …/providers/Microsoft.Authorization/roleDefinitions/<guid>, made with Invoke-AzRestMethod; the scope in the path is the first element of assignableScopes, and the stable API version is 2022-04-01. The same PUT updates the role when the GUID is the same. The alternative is az role definition create --role-definition <file.json>, but with a different JSON layout than REST, so the file from the example needs converting. Either way, the definition is read back immediately after creation (a GET on the same path), each of the four permission lists is compared with the intended ones, and only then is an assignment created.
App registrations and service principals
Registration versus service principal
An app registration (an application object) is a definition: the application identifier (client ID), redirect URIs, the declaration of requested permissions and credentials. It exists in the one tenant where it was created. A service principal (a servicePrincipal object, called an “enterprise application” in the portal) is an instance of that definition in a particular tenant. It receives role assignments, consents and access policies, and its sign-ins are written to the logs.
A single-tenant application has its registration and service principal in the same tenant. A multi-tenant application, for example a vendor’s product, has one registration at the vendor and a separate service principal in every tenant that has granted consent, so in the customer’s tenant the service principal is managed, while the vendor holds the application’s credentials. In the examples, app-crm-sync is a service without a user that reads accounts through Microsoft Graph, and app-intranet signs users in and acts on their behalf.
A client secret created in the portal has a maximum validity of 24 months (a longer term can be set through Microsoft Graph, which is why app management policies are needed), and a registration often outlives the person who created it. When a secret expires the service stops without warning, and the portal shows neither the owner, the place where the secret is stored nor the justification for the permissions.
Credentials: from the best to the last resort
A registration can have a client secret, a certificate or a federated credential; a managed identity is a separate object without a secret. The choice follows from where the code runs:
| Credential | Where the code runs | Rotation | Risk |
|---|---|---|---|
| Managed identity | Azure machines and services, servers with Azure Arc | done by the platform | no secret to leak; the risk lies in the identity’s permissions |
| Federated credential | CI pipeline (GitLab, GitHub), Kubernetes cluster | none, the job token lives for minutes | an overly broad subject opens access to the whole repository |
| Certificate | on-premises server without Arc | replaced before expiry | private key on the host; safe only when non-exportable |
| Client secret | an application that supports nothing else | manual, 24 months at most in the portal | easiest to copy |
Microsoft recommends a certificate instead of a secret and advises against a secret in production; the recommended secret validity is less than 12 months. For code in Azure or on a server with Arc the choice is simple: a managed identity. A CI pipeline needs no secret if its provider issues OIDC tokens; Entra ID then trusts the job token. A federated credential is created by New-MgApplicationFederatedIdentityCredential with the -ApplicationId parameter, which takes the registration’s object ID, not the client ID. The request body has four fields: name, issuer (the CI provider’s address), subject and audiences with the value api://AzureADTokenExchange.
The subject value must exactly match the sub claim in the token, and an error in it produces no message at creation: the token exchange simply fails. The format depends on the provider, so sub is copied from the job token rather than composed by hand; for GitLab it has the form project_path:<group>/<project>:ref_type:branch:ref:main. Wildcards do not work in classic federated credentials, and the limit is 20 credentials per application.
A client secret remains for applications that support nothing else; its validity is then shortened, and the value is stored in a secret manager (Azure Key Vault), not in a configuration file.
Permissions and consent
Delegated permissions act on behalf of the signed-in user and are limited to the intersection of the application’s and the user’s permissions; consent is given by the user or an administrator. Application permissions act without a user across the whole tenant and always require administrator consent. User.Read.All as an application permission lets app-crm-sync read every user, so it is a decision of a weight close to assigning a role, and the list of such permissions needs review.
By default every user can consent to permissions that do not require administrator consent. Microsoft recommends limiting this to applications from verified publishers and permissions classified as low impact. In the portal this is the option “Allow user consent for apps from verified publishers, for selected permissions” (Enterprise apps, Consent and permissions, User consent settings). In Graph the setting is the list of policies in defaultUserRolePermissions.permissionGrantPoliciesAssigned of the authorizationPolicy policy; the microsoft-user-default-low policy corresponds to the recommended option. Before the change the current policy is retrieved and the existing managePermissionGrantsForOwnedResource.* entries are written back, because omitting them removes application owners’ ability to manage consents. The change affects future consents only.
A user whose application requires administrator consent does not have to write to the IT department: the admin consent workflow lets the request be sent from the consent screen to designated reviewers. It is enabled by a Global Administrator (Enterprise apps, Consent and permissions, Admin consent settings). Reviewers can review and deny requests, but in this workflow Microsoft Graph application permissions are approved only by a Global Administrator. When administrator consent is granted directly, a Privileged Role Administrator can also grant Graph application permissions, while Application Administrator and Cloud Application Administrator can grant consent for other permissions but not for these.
App management policies
A requirement such as “a secret no longer than one year” is easy to write in a procedure and hard to enforce. App management policies enforce it in the tenant: they limit the validity of passwords and certificates and can block new secrets. They are set in the portal (Enterprise apps, Application policies) or through Graph; the required roles are Security Administrator together with Application Administrator or Cloud Application Administrator, or Global Administrator. The tenant default policy is changed with Update-MgPolicyDefaultAppManagementPolicy after Connect-MgGraph with the Policy.ReadWrite.ApplicationConfiguration permission; the body contains isEnabled and the restrictions in applicationRestrictions:
| Restriction | Type (restrictionType) | Example limit (maxLifetime) |
|---|---|---|
Password in passwordCredentials | passwordLifetime | P180D (180 days) |
Symmetric key in passwordCredentials | symmetricKeyLifetime | P180D |
Certificate in keyCredentials | asymmetricKeyLifetime | P365D (365 days) |
The maxLifetime parameter is a duration in ISO 8601 format, and restrictForAppsCreatedAfterDateTime limits the policy to applications created after the given date. The portal treats the restriction as a set of four settings (password and symmetric key, separately for applications and for service principals), so a policy written through Graph for only some of them blocks editing in the portal; the same restrictions are added in servicePrincipalRestrictions. The configuration page does not list licences for this feature, so the requirements have to be confirmed in the tenant.
Owners and housekeeping
Every registration should have two owners, and the applications of departing employees have to be reassigned. Applications with fewer than two owners are found by the Graph query applications?$filter=owners/$count eq 0 or owners/$count eq 1&$count=true&$select=id,displayName with the header ConsistencyLevel: eventual. The servicePrincipalSignInActivity report (Graph beta, preview) shows the last use of each application, but in preview it may include partial sign-ins, so the timestamp alone does not prove a successful authentication. An application with no sign-in for 90 days is first disabled and deleted after a grace period, like inactive accounts in Active Directory.
Expiring credentials are detected by a script using Get-MgApplication -All -Property 'id,appId,displayName,passwordCredentials,keyCredentials' (the Application.Read.All permission), which collects the EndDateTime of secrets and certificates and lists those that have expired or will expire within 60 days; a date in the past means the credential is already invalid. Service principal secrets and the SAML certificates of enterprise applications expire independently and need a separate check.
Managed identities instead of keys
A key is a shared secret: anyone who knows it has full access, the resource log does not show who used it, and regenerating it stops every application that was given the same key during testing. A managed identity removes the secret from configuration: the code asks a local endpoint for a Microsoft Entra ID token, and the resource checks the RBAC role of that identity, including on on-premises servers through Azure Arc.
System-assigned or user-assigned
A managed identity is a special type of service principal in Entra ID whose credentials are created and renewed by Azure. There are two kinds:
| Feature | System-assigned | User-assigned |
|---|---|---|
| Creation | enabled on a resource, e.g. a virtual machine | a separate resource, e.g. id-portal-prod-weu |
| Lifecycle | disappears with the resource | exists until someone deletes it |
| Sharing | one resource | many resources, including different types |
| Roles before the resource is deployed | not possible | possible |
Microsoft recommends the user-assigned identity for a wider range of scenarios, because with four machines that have the same permissions to two resources, two role assignments are enough instead of eight. A server with Azure Arc has only a system-assigned identity. Deleting an identity does not delete its role assignments: “Identity not found” entries remain for manual clean-up.
How code obtains a token
The code sends an HTTP request to an endpoint reachable only locally, and the platform returns a token for the resource named in the resource parameter. Each environment has its own endpoint and its own protection against forged requests (SSRF):
| Environment | Token endpoint | What the code must include | api-version |
|---|---|---|---|
| Azure virtual machine | http://169.254.169.254/metadata/identity/oauth2/token (IMDS) | the Metadata: true header | 2018-02-01 or newer |
| App Service | the address in the IDENTITY_ENDPOINT variable | the X-IDENTITY-HEADER header with the value of the IDENTITY_HEADER variable | 2019-08-01 |
| Server with Azure Arc | http://localhost:40342/metadata/identity/oauth2/token (the IDENTITY_ENDPOINT variable) | the Metadata: True header and a response to the challenge | 2020-06-01 (a Windows example) |
With several user-assigned identities the request names the right one with the client_id parameter. The security boundary is the resource: any process on the machine can obtain a token for every identity assigned to it.
Applications use the Azure Identity libraries instead of manual requests. DefaultAzureCredential tries in turn the environment variables with service principal data, the workload identity, the managed identity and only then developer tools, so the same code works on a developer’s workstation and in Azure; ManagedIdentityCredential uses only the managed identity. Calling Azure OpenAI without a key in the Python library means ManagedIdentityCredential(client_id=…) with get_bearer_token_provider(credential, "https://ai.azure.com/.default") passed as the api_key of the OpenAI client, whose base_url has the form https://<resource>.openai.azure.com/openai/v1/. The api_key parameter here accepts a function called before each request, so the token refreshes itself. The Azure OpenAI resource must have its own subdomain, because without one it returns 401.
Role on the target resource
A token opens nothing by itself: Key Vault rejects a valid token if the identity has no role on the vault. The role is usually assigned on a single resource (New-AzRoleAssignment with the identity’s principal ID) and chosen from the data plane roles:
| Resource | Role for the application | What the role does not grant |
|---|---|---|
| Key Vault (RBAC model) | Key Vault Secrets User | changes to secrets, keys and certificates |
| Azure OpenAI | Cognitive Services OpenAI User | managing the resource and deployments |
| Storage account (blobs) | Storage Blob Data Reader or Storage Blob Data Contributor | managing the account and reading account keys |
Owner, Contributor and Storage Account Contributor include the operation that reads storage account keys, so an identity with such a role bypasses the whole model. Roles are assigned directly to the identity, not through a group: tokens are cached on the Azure side for about 24 hours with no way to force a refresh, so a change in group membership may take effect only after many hours.
On-premises server through Azure Arc
The Azure Connected Machine agent creates a server resource in Azure (Microsoft.HybridCompute/machines) and its system-assigned identity, and sets the system variables IDENTITY_ENDPOINT and IMDS_ENDPOINT on the server. The endpoint is reachable by a process with any privileges, but a request that reveals a token requires proof of higher privileges, that is the challenge-response mode: the agent answers the first request with an error carrying the header WWW-Authenticate: Basic realm=<path> that points to a key file, and the code reads the file and repeats the request with the header Authorization: Basic <file contents>. The file can be read only by local administrators and members of the local group Hybrid Agent Extension Applications (the himds group on Linux). The application’s account is added to this group instead of running the application as an administrator. The script (based on the Azure Arc documentation, with the secret read added) runs in Windows PowerShell 5.1:
#Requires -Version 5.1
$endpoint = '{0}?resource={1}&api-version={2}' -f $env:IDENTITY_ENDPOINT, 'https://vault.azure.net', '2020-06-01'
# The first request fails; the header points to the challenge file
$secretFile = ''
try { Invoke-WebRequest -Method GET -Uri $endpoint -Headers @{ Metadata = 'True' } -UseBasicParsing | Out-Null }
catch {
$wwwAuthHeader = $_.Exception.Response.Headers['WWW-Authenticate']
if ($wwwAuthHeader -match 'Basic realm=.+') { $secretFile = ($wwwAuthHeader -split 'Basic realm=')[1] }
}
if (-not $secretFile) { throw 'No challenge from the Azure Arc agent.' }
# The second request with the file contents returns the token
$secret = Get-Content -Raw $secretFile
$response = Invoke-WebRequest -Method GET -Uri $endpoint -UseBasicParsing `
-Headers @{ Metadata = 'True'; Authorization = "Basic $secret" }
$token = (ConvertFrom-Json -InputObject $response.Content).access_token
# Read a secret with the server identity token
$uri = 'https://kv-portal-prod-weu.vault.azure.net/secrets/crm-api-password?api-version=2025-07-01'
(Invoke-RestMethod -Method GET -Uri $uri -Headers @{ Authorization = "Bearer $token" }).value
Code outside Azure and without Arc, for example a pipeline in an external CI system, uses federated credentials instead.
Disabling keys
Moving an application to tokens does not disable keys: as long as they work, anyone who knows them has full access. The order is: check who else uses them, switch those clients, disable the keys and add an Azure Policy that blocks their return. The property depends on the resource type:
| Resource | Setting | What stops working |
|---|---|---|
| Storage account | allowSharedKeyAccess = false | account keys, account SAS and service SAS; user delegation SAS (blobs only) keeps working |
| Azure OpenAI and other Foundry Tools accounts | disableLocalAuth = true | API keys, after propagation that takes from minutes to a few hours |
| Service Bus | disableLocalAuth = true | keys and SAS tokens |
For a storage account a missing value means keys are allowed, and only an explicit false disables them. Disabling account keys cuts the portal off from Azure Files shares if the account has no suitable RBAC assignments, and Cloud Shell from the files on such an account, so accounts with file shares need a separate plan. Who still uses a key is shown by the Transactions metric filtered by Authentication (Account Key, SAS) and by resource logs.
The properties are set by Set-AzStorageAccount -AllowSharedKeyAccess $false, Set-AzCognitiveServicesAccount -DisableLocalAuth $true and Set-AzServiceBusNamespace -DisableLocalAuth; after the first command, requests using the account key, account SAS and service SAS receive 403. The -DisableLocalAuth parameter takes a different form in the last two commands: in Set-AzCognitiveServicesAccount it takes a Boolean value, and in Set-AzServiceBusNamespace it is a switch. So that keys do not return with the next deployment, built-in Azure Policy definitions that block key access are assigned (e.g. “Storage accounts should prevent shared key access”): first with the Audit effect, and with the Deny effect once clients have been switched. Key settings across a subscription are shown by an Azure Resource Graph query (Search-AzGraph, the Az.ResourceGraph module) over the types microsoft.storage/storageaccounts, microsoft.cognitiveservices/accounts and microsoft.servicebus/namespaces, with the columns properties.allowSharedKeyAccess and properties.disableLocalAuth. A good result is false for storage accounts and true for the other types; an empty value means the default, that is keys that still work.
Azure Key Vault: secrets and certificates
A database connection string kept in four copies (application settings, repository, team note, pipeline variable) has no owner, and nobody knows which copy is current. A secret in Key Vault has one location, a role with an owner, a log entry at every read and an event before expiry, but only when the vault is configured correctly.
One vault per application and environment
A vault is a security boundary: whoever has a role on the vault sees everything in it. The documentation recommends a separate vault for each application, region and environment, e.g. kv-portal-prod-weu and kv-portal-test-weu. The name must be globally unique, because it forms the address kv-portal-prod-weu.vault.azure.net. Certificates are stored as certificate objects, not as secrets with a PFX file, because only then does automatic renewal work.
RBAC instead of access policies
The management plane always uses Azure RBAC. The data plane (reading and writing secrets, keys and certificates) uses either RBAC roles or the older access policies stored in the vault itself. From API version 2026-02-01 new vaults use RBAC by default, while existing ones keep their current model until someone changes enableRbacAuthorization. According to the documentation this requires Az PowerShell 16.3.0 or newer (Azure CLI 2.90.0 or newer), and older API versions will be retired on 27 February 2027.
Access policies do not support Privileged Identity Management, so an administrator has standing access rather than access on demand. In that model a user with the Contributor role could grant themselves access to data, whereas in RBAC management roles do not read secrets.
| Who or what | Built-in role | Scope |
|---|---|---|
| Application reading secrets | Key Vault Secrets User | the application’s vault |
| Operator rotating secrets | Key Vault Secrets Officer | the application’s vault |
| Team managing certificates | Key Vault Certificates Officer | the application’s vault |
| Vault maintenance (network, settings) | Key Vault Contributor (management only) | resource group |
| Exceptional access to all data | Key Vault Administrator, through PIM | vault |
| Permanent deletion | Key Vault Purge Operator | subscription |
The documentation advises against assignments on individual secrets; team isolation comes only from a separate vault. The application’s identity receives only Key Vault Secrets User.
The vault is created by New-AzKeyVault with the parameters -EnablePurgeProtection, -SoftDeleteRetentionInDays 90, -NetworkRuleSet (an object from New-AzKeyVaultNetworkRuleSetObject -DefaultAction Deny -Bypass AzureServices -IpAddressRange <range>) and -Tag with owner, environment and cost centre. The New-AzKeyVault documentation contains only the -DisableRbacAuthorization parameter, which switches a vault from RBAC to access policies; there is no separate parameter that enables RBAC. The script therefore ends by reading the EnableRbacAuthorization property through Get-AzKeyVault: the expected result is True, and with an older module the vault may receive access policies, in which case role assignments do not give access to data. In Azure CLI the explicit form is az keyvault create --enable-rbac-authorization true.
Deletion: soft and permanent
Soft delete is always enabled in new vaults. A deleted vault or object can be recovered for 7–90 days (90 by default; the period is chosen only when the vault is created). During that time the name cannot be reused, so a script that recreates the environment fails until the vault is recovered or purged. Recovery does not restore role assignments or Event Grid subscriptions.
Purge protection is optional and off by default. When it is on, nobody, including the subscription owner and Microsoft, can purge a deleted vault or object before the end of the retention period, and it cannot be turned off. Some services that encrypt data with a key from the vault, e.g. Storage, require it to work. For production it is enabled at creation.
Network: firewall and private endpoint
A new vault has the firewall disabled: any address can send a request, and protection comes only from Entra authentication and permissions. For production the network is a second, independent control: a request passes a network check and an RBAC role check, and without a role it ends with a 403 response.
| Setting | Effect | Note |
|---|---|---|
| IP rules | only the listed public IPv4 addresses | up to 1000 rules; private addresses are not allowed |
| Virtual network rules | a subnet with the Microsoft.KeyVault service endpoint | up to 200 rules |
| Private endpoint and public access disabled | access only from the private network | the name still resolves in public DNS, requests are rejected |
Trusted services exception (Bypass AzureServices) | services on Microsoft’s list bypass the firewall | not every Azure service is on the list |
The firewall applies only to the data plane: deploying a secret with an ARM template goes through management.azure.com and is not subject to it. A service outside the trusted list, e.g. Azure DevOps, needs an address rule, a virtual network rule or a private endpoint.
Expiry and renewal
Every change to a secret creates a new version; a reference without a version returns the latest. An expiry date should be set on every secret (-Expires in Set-AzKeyVaultSecret), because without it nothing signals that the password needs changing, and the vault does not rotate the secret itself. Key Vault publishes Event Grid events (SecretNearExpiry arrives 30 days before the date; there are also SecretExpired and the equivalents for certificates and keys). The receiver can be a Logic App, a webhook or an automation that opens a ticket.
For certificates, renewal depends on the source:
| Certificate source | Renewal | What the administrator does |
|---|---|---|
| Integrated authority (DigiCert, GlobalSign) | automatic, end to end | sets the renewal policy |
| Self-signed certificate | automatic | sets the renewal policy |
| Non-integrated authority, e.g. an internal AD CS | manual: the vault generates the key and a CSR | signs the CSR and merges the certificate with the same pending request, otherwise the key will not match |
| PFX import from any authority | manual | imports the new file before expiry |
By default a new certificate is valid for 12 months and renews after 80 per cent of that period; this is changed by Set-AzKeyVaultCertificatePolicy -RenewAtNumberOfDaysBeforeExpiry.
Secret references in applications
App Service and similar services substitute the secret for the setting, without code changes. The reference has the form @Microsoft.KeyVault(VaultName=kv-portal-prod-weu;SecretName=sql-connection), entered as the value of an application setting. The application uses the system-assigned identity by default (another one is named by keyVaultReferenceIdentity) and needs the Key Vault Secrets User role on the vault. A reference without a version is fetched again every 24 hours. A reference that cannot be resolved raises no error: the application receives the literal text @Microsoft.KeyVault(...). With a vault firewall the application must connect through a virtual network, not through a changing public outbound address. Reading a secret on every request easily exceeds the limit of 4000 transactions per 10 seconds per vault (response 429), so a secret is read at start-up and refreshed rarely.
Audit log
The AuditEvent category reaches Log Analytics, a storage account or Event Hubs only after a diagnostic setting is created. Entries contain the operation (SecretGet, CertificateRenew), the identity from the token, the IP address and the response code, also for rejected requests. A KQL query against the AzureDiagnostics table with ResourceProvider == "MICROSOFT.KEYVAULT" and httpStatusCode_d >= 300, excluding 401 on the Authentication operation and summarised by requestUri_s, ResultSignature, CallerIPAddress and _ResourceId, shows failed requests from the last 7 days. The result distinguishes a 403 from an address outside the firewall (a network problem) from a 403 from a permitted address (a missing role); a single 401 on Authentication is ordinary token negotiation.
Decisions and alternatives
| Approach | When it makes sense | Limitation |
|---|---|---|
| Built-in role assigned to a group at a narrow scope | a role with the right set of permissions exists | may grant more than needed (e.g. Contributor instead of a few operations) |
| Custom role | no built-in role fits: it grants too much or too little | the definition has to be maintained and verified after saving; limit of 5000 roles per tenant |
| Role Based Access Control Administrator with a condition | delegating role assignment within a resource group | a role with a condition cannot be delegated through PIM; without a condition it can grant any role |
| User Access Administrator | exceptionally, full access management | broad Microsoft.Authorization/* set |
| User-assigned identity | many resources with the same permissions, roles before deployment | a separate resource to maintain, role assignments remain after deletion |
| System-assigned identity | one resource, lifecycle matching the resource; the only option on a server with Azure Arc | roles only after the resource is created; one resource per identity |
| Key Vault with RBAC roles | new vaults, access on demand through PIM | switching an existing vault invalidates its access policies |
| Key Vault with access policies | only vaults that already exist | no PIM; Contributor can grant itself access to data |
| IP firewall and virtual network rules | access from fixed addresses and subnets | public IPv4 addresses only; a service outside the trusted list needs a separate rule |
| Private endpoint with public access disabled | production with access only from the private network | requires a private network and DNS; the name still resolves publicly |
Order of work
- Permission inventory: Contributor and Owner assignments at subscription scope (
Get-AzRoleAssignmentwith the-Scopeparameter), assignments made to individuals instead of groups, and “Identity not found” entries left by deleted identities. Check: assignments at broad scopes have a justification or are narrowed. - Narrowing permissions: built-in roles assigned to groups at resource group level, and where none fits, a custom role with
assignableScopeslimited to the resource group. Check: after saving, the definition read from the service matches the file in all four lists; only then is the assignment created. Role assignment is delegated with a condition. - Registration housekeeping: two owners per registration, user consent limited to verified publishers and low-impact permissions, the admin consent workflow enabled, an app management policy limiting the validity of secrets and certificates. Check: the query for applications with fewer than two owners and the expiring-credentials script (60 days) return an empty list.
- Application credentials: a managed identity for code in Azure and on servers with Arc, a federated credential for pipelines with an OIDC token (with
subjectnarrowed to a protected branch), a certificate only for servers without Arc, a client secret as a last resort. Check: a token obtained from the local endpoint opens the target resource, and the identity’s role contains only the needed operations. - Key Vault: a separate vault per application and environment with RBAC, purge protection, a firewall and a diagnostic setting. Roles are assigned before an existing vault is switched from access policies. Check:
EnableRbacAuthorizationreturnsTrue, the application reads a secret with the Secrets User role alone, and rejected requests appear inAuditEvent. - Secrets and certificates: expiry dates on every secret, an Event Grid subscription (
SecretNearExpiry,SecretExpired), a certificate renewal policy, a manual procedure for a non-integrated authority, Key Vault references in application settings instead of a copy of the secret. - Disabling keys: a Resource Graph query showing resources with working keys, identifying the clients that use keys (the Transactions metric filtered by Authentication), switching them to tokens, and then
allowSharedKeyAccess = falseanddisableLocalAuth = true. Azure Policy first with the Audit effect, and with the Deny effect once clients have been switched.
Limitations and pitfalls
- Scope of
subjectin a federated credential. Asubjectlimited to a project but not to a branch or environment lets anyone who can run a job in that project, including from a working branch, obtain the application’s permissions. The value is narrowed to a protected branch or a deployment environment. - The
DefaultAzureCredentialchain. It starts with the service principal environment variables, so variables set at system level on a server silently change how every application signs in, and the failure appears only after the secret changes or expires. After deployment to Azure, Microsoft recommends a specific credential, e.g.ManagedIdentityCredential; the chain can also be narrowed with theAZURE_TOKEN_CREDENTIALSvariable (azure-identity 1.23.0 or newer in the Python library). - The identity of an Azure Arc server. Anyone who can run code on the server can use it: local administrators, members of the Hybrid Agent Extension Applications group, and indirectly those who can deploy Arc extensions on the server resource in Azure. The identity is given only the roles needed by the application running there.
- Reading a role definition after creation. The pattern “fetch a built-in role, change
$role.Actionsand create a new one” can produce a different result than expected: in Az.Resources 10.0.0 (Az 16.0.0) the role definition cmdlets moved to thePermissionsarray, and the flattenedActions,NotActions,DataActionsandNotDataActionswere announced for removal as early as 9.0.1. The change log does not describe how an old script behaves, so permissions are read fromPermissions[n].Actionsand so on, and after every creation the lists are compared with the intended ones. - Switching an existing vault to RBAC. It invalidates all access policies, so without previously assigned equivalent roles applications are denied the moment the change is saved. Roles are assigned before the switch, and a new assignment needs a few minutes to propagate.
Sources
- Azure custom roles - Azure RBAC
- Delegate Azure access management to others - Azure ABAC
- Add and manage app credentials in Microsoft Entra ID - Microsoft identity platform
- Configure restrictions on how applications can be configured - Microsoft Entra ID
- Best practice recommendations for managed system identities - Managed identities for Azure resources
- Access Azure resources with managed identity on Azure Arc-enabled servers - Azure Arc
- Plan for Azure RBAC as the default access control model in Key Vault
- Azure Key Vault service limits