The challenge
Preferably, role assignments are automated through privileged release pipelines. The two PowerShell commands that can be used to automate this – New-AzureADServiceAppRoleAssignment and New-AzureADUserAppRoleAssignment – are not easy to use, as it is not always clear what the exact Ids are that you have to provide.
The solution
That’s why I prefer to automate this based on display names and let a script take care of fetching the required Ids. Lately, I have developed such a script to assign Azure AD application roles to users and applications. Hereby, I share it with the community. The script can be found in this gist .
Config file
The script is driven by a simple config file , that contains a JSON array of role assignments:
- description : free text field that describes the role assignment
- client_type : “user” or “application”
- client_principal_name: the users’ UPN ([email protected]) or the display name of the service principal (enterprise application)
- server_app_registration_name : the display name of the app registration to which you want to grant the client access
- role_name the display name of the application role you want to assign to the configured client
{ | |
"description": "Grant Toon administrator access on application Z.", | |
"client_type" : "user", | |
"client_principal_name": "[email protected]", | |
"server_app_registration_name": "app-registration-z-prod", | |
"role_name": "administrator" | |
} |
{ | |
"description": "Grant service principal X reader access on application Z.", | |
"client_type" : "application", | |
"client_principal_name": "service-principal-x-prod", | |
"server_app_registration_name": "app-registration-z-prod", | |
"role_name": "reader" | |
}, |
You can use the script like this:
- Download the script and the config file.
- Update the config files to your needs
- Trigger the script via PowerShell
If you are interested, this is how the script looks like:
param ( | |
[string] $TenantId, | |
[string] $ConfigFilePath | |
) | |
$ErrorActionPreference = "Stop" | |
Write-Host Start Azure AD role assignment script | |
Write-Host "-Tenant Id:" $TenantId -ForegroundColor Gray | |
Write-Host "-Config File Path:" $ConfigFilePath -ForegroundColor Gray | |
Write-Host Installing and importing AzureAD Module | |
if (Get-Module -ListAvailable -Name AzureAD) { | |
Import-Module -Name "AzureAD" | |
} | |
else { | |
Install-Module -Name "AzureAD" -Force | |
} | |
Write-Host Connecting to Azure AD Tenant within current security context | |
$azure_context = Get-AzContext | |
$account_id = $azure_context.Account.Id | |
Write-Host "-Account Id:" $azure_context.Account.Id -ForegroundColor Gray | |
Connect-AzureAD -TenantId $TenantId -AccountId $account_id | |
Write-Host Loading role assignments from config file | |
$role_assignments = (Get-Content $ConfigFilePath -Raw) | ConvertFrom-Json | |
Write-Host Looping each configured role assignment | |
foreach($role_assignment in $role_assignments) | |
{ | |
Write-Host Applying role assigment... started -ForegroundColor Green | |
Write-Host "-Description:" $role_assignment.description -ForegroundColor Gray | |
Write-Host "-Client principal Name:" $role_assignment.client_principal_name -ForegroundColor Gray | |
Write-Host "-Server App Registration Name:" $role_assignment.server_app_registration_name -ForegroundColor Gray | |
Write-Host "-Role Name:" $role_assignment.role_name -ForegroundColor Gray | |
Write-Host Getting the server application registration | |
$aad_filter = "DisplayName eq '" + $role_assignment.server_app_registration_name + "'" | |
$server_application_registration = Get-AzureADApplication -Filter $aad_filter | |
if (!$server_application_registration) { throw "Cannot find configured server application registration with name '" + $role_assignment.server_app_registration_name + "'" } | |
Write-Host Getting the server service principal id | |
$aad_filter = "AppId eq '" + $server_application_registration.AppId + "'" | |
$server_service_principal = Get-AzureADServicePrincipal -Filter $aad_filter | |
$server_service_principal_id = $server_service_principal.ObjectId | |
Write-Host "-Server service principal Id: " $server_service_principal_id -ForegroundColor Gray | |
Write-Host Getting the Id for the configured application role | |
$role_id = ($server_application_registration.AppRoles | Where-Object DisplayName -eq $role_assignment.role_name).Id | |
if (!$role_id) { throw "Cannot find configured application role with name '" + $role_assignment.role_name + "'" } | |
Write-Host "-Role Id: " $role_id -ForegroundColor Gray | |
if(($role_assignment.client_type -ne "application") -and ($role_assignment.client_type -ne "user")) { throw "Incorrect client_type '" + $role_assignment.client_type + "' provided." } | |
switch ($role_assignment.client_type) | |
{ | |
"application" | |
{ | |
Write-Host Getting the configured client service principal | |
$aad_filter = "DisplayName eq '" + $role_assignment.client_principal_name + "'" | |
$client_service_principal = (Get-AzureADServicePrincipal -Filter $aad_filter) | |
if (!$client_service_principal) { throw "Cannot find configured client service principal with name '" + $role_assignment.client_principal_name + "'" } | |
$client_service_principal_id = $client_service_principal.ObjectId | |
$client_service_principal_name = $client_service_principal.DisplayName | |
Write-Host "-Client service principal Id:" $client_service_principal_id -ForegroundColor Gray | |
Write-Host Assigning the Azure Ad role to the configured service principal | |
try | |
{ | |
New-AzureADServiceAppRoleAssignment -Id $role_id -ResourceId $server_service_principal_id -ObjectId $client_service_principal_id -PrincipalId $client_service_principal_id | |
} | |
catch | |
{ | |
if( $_.Exception.Message -like '*Permission being assigned already exists on the object*') | |
{ | |
Write-Host Permission already exists | |
} | |
else | |
{ | |
Write-Error $_.Exception.Message | |
} | |
} | |
} | |
"user" | |
{ | |
Write-Host Getting the configured client user | |
$user = Get-AzureADUser -searchstring $role_assignment.client_principal_name | |
if (!$user) { throw "Cannot find configured client users with name '" + $role_assignment.client_principal_name + "'" } | |
$user_id = $user.ObjectId | |
Write-Host "-User Id:" $user_id -ForegroundColor Gray | |
Write-Host Assigning the Azure Ad role to the configured user | |
try | |
{ | |
New-AzureADUserAppRoleAssignment -Id $role_id -ResourceId $server_service_principal_id -ObjectId $user_id -PrincipalId $user_id | |
} | |
catch | |
{ | |
if( $_.Exception.Message -like '*Permission being assigned already exists on the object*') | |
{ | |
Write-Host Permission already exists | |
} | |
else | |
{ | |
Write-Error $_.Exception.Message | |
} | |
} | |
} | |
} | |
Write-Host Applying role assigment... done -ForegroundColor Green | |
} |
I hope that this script helps you to accelerate your security automation.
Cheers Toon
UPCOMING TRAININGS
CHECK OUT OUR TRAININGS
Azure Integration Services
Azure migration.
- Azure Governance
Azure Security
Azure foundations, recent posts.
- Looking back at INTEGRATE 2024
- Azure Service Bus vs Event Grid Pull Delivery
- Trying the new Microsoft Applied Skills
- Finally a correct way to configure RBAC for DevOps agents!
- What do the new API Management v2 tiers mean for you?
- Announcement
- API Management
- Architecture
- Azure App Service
- Azure Data Factory
- Azure DevOps
- Azure Event Grid
- Azure Functions
- Azure Kubernetes Service
- Azure Policy
- Azure Resource Graph
- Azure Resource Manager
- Azure Service Bus
- Azure Stream Analytics
- BizTalk Server
- Container Apps
- Geen categorie
- Home Automation
- Microsoft Learn
- Service Bus
MEET THE YOUR AZURE COACH TEAM
Your Azure Coach is specialized in organizing Azure trainings that are infused with real-life experience. All our coaches are active consultants, who are very passionate and who love to share their Azure expertise with you.
Toon Vanhoutte
Azure integration services & serverless.
Wim Matthyssen
Azure infra, security & governance, azure development and ai/ml, azure identity and security, stéphane eyskens, cloud-native azure architecture, geert baeke, azure kubernetes service & containerization, maik van der gaag, azure infrastructure as code & devops, bart verboven, sammy deprez, azure ai, ml & cognitive services, sander van de velde.
Software Engineering
- ASP.NET Core
- Elasticsearch
- Entity Framework
Implement app roles authorization with Azure AD and ASP.NET Core
This post shows how to implement Azure AD App roles and applied to users or groups in Azure AD. The roles are used in an ASP.NET Core Razor page application as well as a ASP.NET Core API. The roles from the access token and the id token are used to authorize the identity which is authenticated.
Code: App roles
Create an Azure App registration for Web APP
In this example, a web application will implement authentication and will use a second ASP.NET Core application which implements the user API. Two Azure AD App registrations are created for this, one for each application.
The ASP.NET Core Razor page application is a client which can be authenticated, as well as the identity using the application. It has a trusted back end which can keep a secret. The Azure AD App registration uses a standard web application with a client secret. You could also use a certificate instead of a secret to authenticate the client.
App roles are added to the App registration for the UI client. These roles are used in the UI application which are returned in a user data profile request or in the id token, depending how your client implemented the OIDC standard.
Three roles were added to the Azure AD App registration using the App roles | preview blade.
The roles could also be added directly in the manifest json file.
The API permissions are setup to include the scope created in the API Azure AD App registration. The standard OIDC scopes are added to the registration. All scopes are delegated scopes.
Create an Azure App registration for Web API
The App registration used for the API implements NO authentication flows. This App registration exposes an API and defines roles for the API project authorization. An access_as_user scope is added to the Azure App registration which is a delegated scope type.
Three roles were added to the Azure AD App registration for the API. These roles are for the API and will be added to the access token if the identity has been assigned the roles in the enterprise application of the Azure AD directory. The roles could also be added directly in the manifest.
Apply roles in Azure AD enterprise applications
The new roles which were defined in the Azure AD App registration can now be used. This is setup in the Enterprise application blade of the Azure AD directory. In the Enterprise application list, select the App registration for the API. New users or groups can be added here, and the roles can then be assigned.
In the Add user/group a user or a group can be selected (! Groups can only be selected if you have the correct license) and the roles which were created in the Azure AD App registration can be applied.
If creating applications for tenants with lots of users, groups would be used.
Implement ASP.NET Core API
The API is implemented in ASP.NET Core . The startup class is used to setup the authorization of the access tokens. The Microsoft.Identity.Web Nuget package is used for this. This application configuration will match the configuration of the Azure AD App registration setup for the API. The AddMicrosoftIdentityWebApiAuthentication method is used for this.
ASP.NET Core adds namespaces per default to the claims which are extracted from the access token. We do not want this and so disable the default claim mapping. The roles and the name can should also be mapped, as the default setting does not match what Azure AD returns in the token.
Authorization is added for the API using the AddAuthorization method or it can be added global as a filter. The roles claims are mapped to policies which can then be enforced throughout the application. You could also do this directly using the roles property in the authorize attribute, but I prefer to use policies and separate the authorization. Only policies are used in the application.
A ValidateAccessTokenPolicy policy is implemented to do validation on the access token. The scp claim is validated for an access_as_user value as this is a user API for delegated access and not an application token. The azp claim is used to validate the client calling the API. The API is made specifically for the UI application and so we can validate that only access tokens created for the UI application can use this API. The azp claim is only sent in version 2 Azure App registrations. You must set this in the manifest.
The azpacr claim is also validated. Only authenticated clients can use this API. Any application which gets an access token for this API must use a secret as the value of “1” is controlled. This ensures that public clients cannot create access tokens for this API. If this was a value of “2”, only clients which used certificates to authenticate can acquire access tokens for this API.
It is good to validate the intended user, if possible.
Authorization can also be added globally as a filter in the AddControllers. This would be applied to this middleware.
The policies can then be applied in the API application as required. The access token used to access the API must fulfil all policies used on the API endpoint. If any single policy fails, the a 403 forbidden is returned.
Implement ASP.NET Core Razor Page APP
The ASP.NET Core Razor Page application uses an OIDC interactive flow to authenticate using Azure AD as the identity provider. Both the client application and the identity are authenticated. Microsoft.Identity.Web is used to implement the client code which uses Open ID connect. The AddMicrosoftIdentityWebAppAuthentication method is used in the Startup class in the ConfigureServices method. The downstream APIs are enabled as well as in memory cache. In memory cache is a bit of a problem with testing, as you need to delete the cookies in the browser manually after every test run. You can fix this by using a persistent cache. A filter is added so that an authenticated user is required.
The app.settings.json file contains the configurations for the Azure AD authentication of the application which uses the Microsoft.Identity.Web client. The ClientId from the Web APP App registration and the TenantId for the directory are added here. The ClientSecret also needs to be defined. This should be added to the user secrets in development or added to an Azure Key Vault if deploying to Azure. The ApiWithRoles configuration added the API scope and the URL for the API.
The GetDataFromApi method calls the APIs. The UI application can call any one of the APIs, user, student or admin, each which required a different role. The policies were applied to these APIs. If an error is returned, the exception is handled and returned as a list to demonstrate. The ITokenAcquisition interface is used to get the access token from cache or from the Azure AD identity provider and the access token is added to the Authorization header of the HTTP request as a Bearer token.
To demonstrate the application, the user has been assigned the user “web-api-with-roles-user” and the “web-api-with-roles-admin” roles but not the “web-api-with-roles-student” for the API access. The “web-app-with-roles-user” was assigned for the UI application.
After a successful authentication, the claims from Azure AD are added to the HttpContext.User. A single roles claim (“web-app-with-roles-user”) is added for the UI application. This is as we expected.
If the API is called, the access token can be extracted from the debugger and pasted to jwt.ms or jwt.io . The access token contains two roles, “web-api-with-roles-user”, “web-api-with-roles-admin” as was configured in the enterprise application for this user. The access token also has the scp claim with the access_as_user . The azp claim and the azpacr claims have the expected values. A secret was using to signin to the client UI application which we allow.
A breakpoint was added to Visual Studio in the API project and the claims from the access token can be inspected. We expect the same values like in the access token and without the ASP.NET Core extras.
The ASP.NET Core UI application displays the results of the three API calls. The user and the admin APIs return data and the student API returns a forbidden result. This is what was configured. Now if the user is assigned new roles, after a logout, login, the new claims will be included in the tokens.
This approach works well if you do not have many roles, groups or claims, or if you do not need to change the authorization without re-authentication. The size of the access_token is important, this should not become large. If you require lots of claims for the authorization rules, the claims should not be included in the access token and Microsoft Graph API could be used to access these, or you could implement your own policy management.
https://docs.microsoft.com/en-us/azure/architecture/multitenant-identity/app-roles
https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-enterprise-app-role-management
https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/5-WebApp-AuthZ/5-1-Roles
https://docs.microsoft.com/en-us/azure/active-directory/develop/microsoft-identity-web
https://github.com/AzureAD/microsoft-identity-web
https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens
https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens
Restricting access to an Azure AD protected API using Azure AD Groups
https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies
Share this:
10 comments.
[…] Implement app roles authorization with Azure AD and ASP.NET Core – Damien Bowden […]
Thank you for the agreat post,
When WebAppWithRoles calls WebApiWithRoles returns an forbidden as result . Can you place explain how you configured web apps claims as azp, azpacr, roles”: [ “web-api-with-roles-user”, “web-api-with-roles-admin” ], and scp to the access token
Unable to run the application end-to-end…. Would appreciate some tips..
Sorry for the slow reply, just saw this now. The Azure App registrations need to be added from your tenants Azure App registration as well as the secrets
Nice tutorial.
Did you map users/groups in the SPA Enterprise App AND in the Api Enterprise App?
or did you only do it in the Api Enterpise App?
thanks, yes
It sounds like a problem from a maintenance point of view. Lets say you add the correct roles to the SPA for a user, but forgets one role on the API.
Then the user will be presented with some functionality, but when he tries to use it, he will get a 403 from the API.
I also asked this question in the msal library: https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/4389
But not sure what the best strategy is to tackle this problem
I normally do this with security groups. The groups roles and APP are setup once at the start. The I restrict access to the Enterprise APP. Then you only need to assign or remove users from the security groups. But this is not black and white. You need too think about lifespan of the roles, where these belong and so on. No authz is ever the same. I would need to analyze this in more detail for your setup. Greetings Damien
[…] También revisa esto Implementar la autorización de roles de aplicaciones con Azure AD y ASP.NET Core | Ingeniería de S… […]
Can you kindly suggest changes to above required for App Role (application)
Leave a comment Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed .
blogs 1 web, general
- Andrew Lock
- Anthony Giretti
- ASP.NET Core blog
- Benjamin Abt (de)
- Bryan Hogan
- Claudio Bernasconi
- code-maze.com
- Davide Bellone
- dotnetcore tutorials
- dotnetthoughts
- Fabian Gosebrink
- Filip WOJCIESZYN
- Gérald Barré
- Gunnar Peipman's
- haacked.com
- Isaac Abraham
- Isaac Levin
- Jürgen Gutsch
- Jeremy Likness
- João Antunes
- josef.codes
- joseph guadagno
- Jussi Roine
- khalid abuhakmeh
- Laurent Kempé
- mikesdotnetting
- Morning brew
- Niels Swimburger
- Ramani Sandeep
- Rockford Lhotka
- Scott Hanselman
- Shawn Wildermuth
- Steve Gordon
- thomas claudius huber
- Tobias Zimmergren
blogs 2 security
- Ackermann Yuriy
- Azure security podcast
- Bárbara Vieira
- Daniel Fett
- Daniel Miessler
- Dominick Baier
- Elie Bursztein
- futurae.com
- James Kettle
- John Patrick Dandison
- Justin Richer
- Kévin Chalet
- Kevin Dockx
- Matthijs Hoekstra
- Michal Špaček
- Microsoft Secure
- Mike Jones self-issued
- Nat Sakimura
- Philippe De Ryck
- research.kudelskisecurity
- Robert Broeckelmann
- Rory Braybrook
- Scott Brady
- Scott Helme
- securityguill
- sirdarckcat
- Stephen Haunts
- Steve Syfuhs
- Takahiko Kawasaki
- Tanya Janca
- Torsten Lodderstedt
blogs 3 Azure
- Alexandre Verkinderen
- Anthony Chu
- Azure DevOps
- Boris Wilhelms
- cloud-architekt.net
- cloudbrothers
- daniel chronlund
- Daniel Krzyczkowski
- Dominique St-Amand
- Eduard Keilholz
- francois leon
- Gareth Emslie
- Jan de Vries
- jeffrey appel
- Joonas Westlin
- Mahindra Morar
- Marius Solbakken
- Martin Lingstuyl
- Mickaël Derriey
- o365blog Dr Nestori Syynimaa
- olivier vaillancourt
- René Bremer
- Rick van den Bosch
- Sahil Malik
- Stephan van Rooij
- Stephane Eyskens
- Stian A. Strysse
- thomas maurer
- Thomas Naunheim
- Toon Vanhoutte
blogs 4 SSI DID
- hyperledger
- hyperledger aries-framework-dotnet
- identity.foundation
- identity.foundation blog
- idunion.org
- Kaliya-Identity Woman
- Kim Hamilton Duffy
- Kyle Den Hartog
- Markus Sabadello
- mattr.global
- Microsoft DID
- newsletter.identosphere.net
- Phillip J. Windley
- ssi-orbit-podcast
- Tomislav Markovski
- Andreas Helland
- Damien Guard
- Dan Wahlin's
- Data Farm Julie Lerman
- Dave Paquette
- Development With A Dot
- Elton Stoneman
- exceptionnotfound.net
- jeff handley
- Jeffrey T. Fritz
- Juan Carlos Sanchez's
- Maarten Balliauw
- Manfred Steyer (de)
- Manuel Meyer
- Mete Atamel
- Minko Gechev
- Nate Barbettini
- Nicholas Blumhardt
- Pawel Kadluczka
- Rui Figueiredo
- Stefan Prodan
- Stephen Cleary
- Alexander Beletsky
- Anders Janmyr
- Anže Vodovnik
- chsakell's Blog
- Florian Hopf
- fredrik normén
- Galdin Raphael
- Gernot Starke (de)
- Imran Baloch
- Jalpesh Vadgama DotNetJalps
- Jeffrey Palermo
- Jimmy Nilsson
- job tips for geeks
- Johnny Graber (de)
- Jon Galloway
- Kevin Jones
- Laurent Bugnion
- Linda Lawton
- Mick Taulty
- Muhammad Rehan Saeed
- PPEDV blog (de)
- Rashim's Blog
- Scott Addie
- scottgu .NET
- Shayne Boyer
- steven sanderson
- Taiseer Joudeh
- Thomas Ardal
- Thomas Levesque
- Tugberk Ugurlu
- .NET (Core, 5+ ) SDK
- Angular CLI
- bootstrap 4
- gitextensions
- IDP Azure AD
- IDP DuendeSoftware
- IDP keycloak
- IDP node-oidc-provider
- IDP OpenIddict
- lets encrypt
- protobuf-net
- randommer.io
- Search elasticsearch
- Search Solr
- Test achecker.ca
- Test DotTrace Profiler
- Test FakeItEasy
- Test Fiddler
- Test mkjwk.org JSON Web Key
- Test Ndepend
- Test Sysinternals Suite
- Test wireshark
- Test xunit.net
- Test zaproxy
- Visual Studio
- Visual Studio Code
- .NET Group Basel
- .NET Group Bern (de)
- .NET Group Luzern (de)
- .NET Group Zürich
- .NET User Group Geneva
- Angular Switzerland
- blackhat.com
- Brice's Entity Links
- Christian Mosers
- Code Project
- devcurry Suprotim Agarwal
- developer.chrome
- Fabrice Bellard
- fido alliance
- jeremy skinner
- Martin Fowler
- one unicorn
- OPC Foundation
- rob tiffany
- Simple Talk Red Gate
- thinktecture
- Thoughtworks Radar
- tutorialzine
- Web Fundamentals
- Entries feed
- Comments feed
- WordPress.com
- September 2024
- August 2024
- February 2024
- January 2024
- December 2023
- November 2023
- October 2023
- September 2023
- August 2023
- February 2023
- January 2023
- December 2022
- November 2022
- October 2022
- September 2022
- August 2022
- February 2022
- January 2022
- December 2021
- November 2021
- October 2021
- September 2021
- August 2021
- February 2021
- January 2021
- December 2020
- November 2020
- October 2020
- September 2020
- August 2020
- February 2020
- January 2020
- December 2019
- November 2019
- October 2019
- September 2019
- August 2019
- February 2019
- January 2019
- December 2018
- November 2018
- October 2018
- September 2018
- August 2018
- February 2018
- January 2018
- December 2017
- November 2017
- October 2017
- September 2017
- August 2017
- February 2017
- January 2017
- December 2016
- November 2016
- October 2016
- September 2016
- August 2016
- February 2016
- January 2016
- December 2015
- November 2015
- October 2015
- September 2015
- August 2015
- February 2015
- January 2015
- December 2014
- November 2014
- October 2014
- September 2014
- August 2014
- February 2014
- January 2014
- December 2013
- November 2013
- October 2013
- September 2013
- August 2013
- February 2013
- January 2013
- Already have a WordPress.com account? Log in now.
- Subscribe Subscribed
- Copy shortlink
- Report this content
- View post in Reader
- Manage subscriptions
- Collapse this bar
Manage Azure Role Assignments Like a Pro with PowerShell
Today’s blog post is a little bit different. I have a couple of examples of how you can use PowerShell snippets and simple commandlets to get or set role assignmnets in your Azure Subscriptions.
PowerShell examples for managing Azure Role assignments
List all role assignments in a subscription, get all role assignments for a specific resource group, get all role assignments for a specific user, add a role assignment to a user, remove a role assignment for a user, remove all role assignments for a specific user, list all built-in roles, list all custom roles, create a custom role, update a custom role, delete a custom role, list all users or groups assigned to a specific role, list all permissions granted by a specific role, list all resource groups that a user has access to, create a role assignment for a service principal, powershell script to manage azure role assignments.
And now there is a script that combines some of these examples into one usable function:
I hope this was useful. Let me know if you liked the format of this blog and if you want me to include more of these examples.
Vukasin Terzic
Recent Update
- Writing your first Azure Terraform Configuration
- Transition from ARM Templates to Terraform with AI
- Getting started with Terraform for Azure
- Terraform Configuration Essentials: File Types, State Management, and Provider Selection
- Dynamically Managing Azure NSG Rules with PowerShell
Trending Tags
Retrieve azure resource group cost with powershell api.
The Future Of Azure Governance: Trends and Predictions
Further Reading
In my previous blog posts, I wrote about how simple PowerShell scripts can help speed up daily tasks for Azure administrators, and how you can convert them to your own API. One of these tasks is...
Azure Cost Optimization: 30 Ways to Save Money and Increase Efficiency
As organizations continue to migrate their applications and workloads to the cloud, managing and controlling cloud costs has become an increasingly critical issue. While Azure provides a robust s...
Custom PowerShell API for Azure Naming Policy
To continue our PowerShell API series, we have another example of a highly useful API that you can integrate into your environment. Choosing names for Azure resources can be a challenging task. ...
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Assign Azure roles using Azure CLI
- 10 contributors
Azure role-based access control (Azure RBAC) is the authorization system you use to manage access to Azure resources. To grant access, you assign roles to users, groups, service principals, or managed identities at a particular scope. This article describes how to assign roles using Azure CLI.
Prerequisites
To assign roles, you must have:
- Microsoft.Authorization/roleAssignments/write permissions, such as Role Based Access Control Administrator
- Bash in Azure Cloud Shell or Azure CLI
Steps to assign an Azure role
To assign a role consists of three elements: security principal, role definition, and scope.
Step 1: Determine who needs access
You can assign a role to a user, group, service principal, or managed identity. To assign a role, you might need to specify the unique ID of the object. The ID has the format: 11111111-1111-1111-1111-111111111111 . You can get the ID using the Azure portal or Azure CLI.
For a Microsoft Entra user, get the user principal name, such as [email protected] or the user object ID. To get the object ID, you can use az ad user show .
For a Microsoft Entra group, you need the group object ID. To get the object ID, you can use az ad group show or az ad group list .
Service principal
For a Microsoft Entra service principal (identity used by an application), you need the service principal object ID. To get the object ID, you can use az ad sp list . For a service principal, use the object ID and not the application ID.
Managed identity
For a system-assigned or a user-assigned managed identity, you need the object ID. To get the object ID, you can use az ad sp list .
To just list user-assigned managed identities, you can use az identity list .
Step 2: Select the appropriate role
Permissions are grouped together into roles. You can select from a list of several Azure built-in roles or you can use your own custom roles. It's a best practice to grant access with the least privilege that is needed, so avoid assigning a broader role.
To list roles and get the unique role ID, you can use az role definition list .
Here's how to list the details of a particular role.
For more information, see List Azure role definitions .
Step 3: Identify the needed scope
Azure provides four levels of scope: resource, resource group , subscription, and management group . It's a best practice to grant access with the least privilege that is needed, so avoid assigning a role at a broader scope. For more information about scope, see Understand scope .
Resource scope
For resource scope, you need the resource ID for the resource. You can find the resource ID by looking at the properties of the resource in the Azure portal. A resource ID has the following format.
Resource group scope
For resource group scope, you need the name of the resource group. You can find the name on the Resource groups page in the Azure portal or you can use az group list .
Subscription scope
For subscription scope, you need the subscription ID. You can find the ID on the Subscriptions page in the Azure portal or you can use az account list .
Management group scope
For management group scope, you need the management group name. You can find the name on the Management groups page in the Azure portal or you can use az account management-group list .
Step 4: Assign role
To assign a role, use the az role assignment create command. Depending on the scope, the command typically has one of the following formats.
The following shows an example of the output when you assign the Virtual Machine Contributor role to a user at a resource group scope.
Assign role examples
Assign a role for all blob containers in a storage account resource scope.
Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at a resource scope for a storage account named storage12345 .
Assign a role for a specific blob container resource scope
Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at a resource scope for a blob container named blob-container-01 .
Assign a role for a group in a specific virtual network resource scope
Assigns the Virtual Machine Contributor role to the Ann Mack Team group with ID 22222222-2222-2222-2222-222222222222 at a resource scope for a virtual network named pharma-sales-project-network .
Assign a role for a user at a resource group scope
Assigns the Virtual Machine Contributor role to [email protected] user at the pharma-sales resource group scope.
Assign a role for a user using the unique role ID at a resource group scope
There are a couple of times when a role name might change, for example:
- You are using your own custom role and you decide to change the name.
- You are using a preview role that has (Preview) in the name. When the role is released, the role is renamed.
Even if a role is renamed, the role ID does not change. If you are using scripts or automation to create your role assignments, it's a best practice to use the unique role ID instead of the role name. Therefore, if a role is renamed, your scripts are more likely to work.
The following example assigns the Virtual Machine Contributor role to the [email protected] user at the pharma-sales resource group scope.
Assign a role for all blob containers at a resource group scope
Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 at the Example-Storage-rg resource group scope.
Assign a role for an application at a resource group scope
Assigns the Virtual Machine Contributor role to an application with service principal object ID 44444444-4444-4444-4444-444444444444 at the pharma-sales resource group scope.
Assign a role for a new service principal at a resource group scope
If you create a new service principal and immediately try to assign a role to that service principal, that role assignment can fail in some cases. For example, if you use a script to create a new managed identity and then try to assign a role to that service principal, the role assignment might fail. The reason for this failure is likely a replication delay. The service principal is created in one region; however, the role assignment might occur in a different region that hasn't replicated the service principal yet. To address this scenario, you should specify the principal type when creating the role assignment.
To assign a role, use az role assignment create , specify a value for --assignee-object-id , and then set --assignee-principal-type to ServicePrincipal .
The following example assigns the Virtual Machine Contributor role to the msi-test managed identity at the pharma-sales resource group scope:
Assign a role for a user at a subscription scope
Assigns the Reader role to the [email protected] user at a subscription scope.
Assign a role for a group at a subscription scope
Assigns the Reader role to the Ann Mack Team group with ID 22222222-2222-2222-2222-222222222222 at a subscription scope.
Assign a role for all blob containers at a subscription scope
Assigns the Storage Blob Data Reader role to the [email protected] user at a subscription scope.
Assign a role for a user at a management group scope
Assigns the Billing Reader role to the [email protected] user at a management group scope.
- List Azure role assignments using Azure CLI
- Use the Azure CLI to manage Azure resources and resource groups
Was this page helpful?
Additional resources
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Azure DevOps ServiceConnection Roles Rest API
How can I modify Azure DevOps ServiceConnection Roles using the REST API?
This is the corresponding UI
I want to add a team within the 'User' role.
I have been looking at
- https://learn.microsoft.com/en-us/rest/api/azure/devops/security/security%20namespaces?view=azure-devops-rest-5.1
- https://learn.microsoft.com/en-us/rest/api/azure/devops/security/access%20control%20lists?view=azure-devops-rest-5.1
is this the right direction?
- azure-devops
- azure-devops-rest-api
2 Answers 2
You can use below api to update security for service connection.
The API is not documented. But you can find it when you F12 your browser.
You can get the resourceId from the request url in F12 page.
Below is example in powershell scripts:
Above script with assign the user to User role permission for the service connection.
You can get the user id from the request body in F12 page. But you may still need to use below rest api to get the user id
- I would like to add one AAD group as role "User" what will be the Body? tried to use AAD Group Object Id as Userid but not working. Can you suggest? – learner Commented May 17, 2022 at 9:49
watch out for the url... this contains the ProjectId_ServiceEndpointId
ProjectId from
UserId from [property: originId]
ServiceEndpointId from
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Sign up or log in
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Not the answer you're looking for? Browse other questions tagged azure-devops azure-devops-rest-api or ask your own question .
- The Overflow Blog
- Masked self-attention: How LLMs learn relationships between tokens
- Deedy Das: from coding at Meta, to search at Google, to investing with Anthropic
- Featured on Meta
- User activation: Learnings and opportunities
- Preventing unauthorized automated access to the network
- Feedback Requested: How do you use the tagged questions page?
Hot Network Questions
- Remove an entire inner list that has any zeros
- Information about novel 'heavy weapons'
- In a shell script, how do i wait for a volume to be available?
- How can I reduce server load for a WordPress website with a large number of visitors without upgrading hosting?
- Why do evacuations result in so many injuries?
- When does derived tensor product commute with arbitrary products?
- Are logic and mathematics the only fields in which certainty (proof) can be obtained?
- Best way to replace a not yet faild drive
- Does history possess the epistemological tools to establish the occurrence of an anomaly in the past that defies current scientific models?
- Is it ethical to edit grammar, spelling, and wording errors in survey questions after the survey has been administered, prior to publication?
- Is a 1500w inverter suitable for a 10a portable band saw?
- What is the origin of the many extra mnemonics in Manx Software Systems’ 8086 assembler?
- In big band horn parts, should I write double flats (sharps) or the enharmonic equivalent?
- All of them in order
- Are file attachments in email safe for transferring financial documents?
- How does a rotating system behave as mass varies?
- Which ancient philosopher compared thoughts to birds?
- Do we have volitional control over our level of skepticism?
- what is the proper order for three verbs at the end of a sentence when there is no ersatz infinitive?
- Letter of Recommendation for PhD Application from Instructor with Master Degree
- Matter made of neutral charges does not radiate?
- 2 NICs, PC is trying to use wrong one
- What is the role of this suffix for an opamp?
- In the Silmarillion or the Appendices to ROTK, Do the Dwarves of Khazad-dûm know about the Balrog below prior to Durin receiving the ring?
IMAGES
VIDEO
COMMENTS
Operations. Create or update a role assignment by scope and name. Create or update a role assignment by ID. Delete a role assignment by scope and name. Delete a role assignment by ID. Get a role assignment by scope and name. Get a role assignment by ID. List all role assignments that apply to a resource. List all role assignments that apply to ...
Azure role-based access control (Azure RBAC) is the authorization system you use to manage access to Azure resources. To grant access, you assign roles to users, groups, service principals, or managed identities at a particular scope. This article describes how to assign roles using the REST API. Prerequisites. To assign Azure roles, you must have:
List role assignments. In Azure RBAC, to list access, you list the role assignments. To list role assignments, use one of the Role Assignments Get or List REST APIs. To refine your results, you specify a scope and an optional filter. Within the URI, replace {scope} with the scope for which you want to list the role assignments.
To get the role definition name, you need to make separate REST API calls and then perform a join on the client side. If you run a network capture while running the Azure PowerShell or Azure CLI, it is straightforward to see the REST API calls. List Role Assignments
Lately, I have developed such a script to assign Azure AD application roles to users and applications. Hereby, I share it with the community. The script can be found in this gist. Config file. The script is driven by a simple config file, that contains a JSON array of role assignments: description: free text field that describes the role assignment
Azure Administrators often come across challenges while tracking multiple Azure role assignments and removals. At present Azure provides Activity Logs but they make less sense to non-techsavy stakeholders. For example it includes Role Id, Principal Id but doesn't indicate Role names and Principal names which can make the report more readable.
from azure.identity import DefaultAzureCredential from azure.mgmt.authorization import AuthorizationManagementClient """ # PREREQUISITES pip install azure-identity pip install azure-mgmt-authorization # USAGE python role_assignments_create_for_resource_group.py Before run the sample, please set the values of the client ID, tenant ID and client ...
In this example, a web application will implement authentication and will use a second ASP.NET Core application which implements the user API. Two Azure AD App registrations are created for this, one for each application. The ASP.NET Core Razor page application is a client which can be authenticated, as well as the identity using the application.
This custom role would allow users to perform all default owner operations except deleting APIM services in the subscription. Step 1: Maneuver to the Access Control (IAM) blade of a sample APIM service on the Azure Portal and click on the Roles tab. This would display the list of roles that are available for assignment.
Azure API Management relies on Azure role-based access control (Azure RBAC) to enable fine-grained access management for API Management services and entities (for example, APIs and policies). This article gives you an overview of the built-in and custom roles in API Management. For more information on access management in the Azure portal, see ...
Figure 2: Select role. Step 2: On the Members tab, select the user you want to delegate the role assignments task to. Figure 3: Select members. Step 3: On the Condition tab, click Add condition to add the condition to the role assignment. Figure 4: Add condition to role assignment. Step 4: On the Add role assignment condition page, specify how ...
The scope at which the role is assigned. The name of the role assignment, and a description that helps you to explain why the role has been assigned. For example, you can use Azure RBAC to assign roles like: User Sally has owner access to the storage account contoso123 in the resource group ContosoStorage. Everybody in the Cloud Administrators ...
Learn how to manage Azure Role assignments using PowerShell snippets and simple commandlets. Discover examples for listing all role assignments, adding and removing assignments for users or service principals, creating custom roles, and more. Plus, check out a script that combines some of these examples into a single function. Written by Vukasin Terzic.
To assign a role, you might need to specify the unique ID of the object. The ID has the format: 11111111-1111-1111-1111-111111111111. You can get the ID using the Azure portal or Azure CLI. User. For a Microsoft Entra user, get the user principal name, such as [email protected] or the user object ID.
Navigate to the resource/resource group/subscription in the portal -> Access control (IAM) -> Role assignments, you can filter with the parameters you want. Or you can use the Azure powershell Get-AzRoleAssignment or REST API, it depends on your requirement. Sample: 1.You have a list of ObjectIds of the users, you can use the script as below.
Above script with assign the user to User role permission for the service connection. You can get the user id from the request body in F12 page. But you may still need to use below rest api to get the user id