avatar

Manage Azure Role Assignments Like a Pro with PowerShell

Azure Governance Future Trends and Predictions - AzureIs.Fun

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. ...

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings
  • Career Model
  • Proactive Mentorship
  • Productivity
  • Review Model
  • Work:Life Balance
  • 3D Printing
  • Announcements
  • Conferences

How to find all the Azure Built-In Roles for Azure RBAC with Azure CLI, PowerShell, Docs, or AzAdvertizer

Here are a bunch of ways you can find which roles are built into Azure. This will come in super handy when you need to assign a role to a service principal or user with Azure CLI commands like this:

  • Query the big honking json
  • Query all, but only return Name and Id in a nice table
  • Filter by name contains:

This one filters for roles with “Map” in the name:

Azure PowerShell

https://docs.microsoft.com/en-us/powershell/module/az.resources/get-azroledefinition?view=azps-3.8.0

This page has all the built in roles: https://docs.microsoft.com/azure/role-based-access-control/built-in-roles

AzAdvertizer

Just found this site today by Julian Hayward. It’s a great way to find roles

https://www.azadvertizer.net/azrolesadvertizer_all.html

'AzAdvertizer'

role assignment list

  • 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.

Where are the az role assignments listed

I assigned a Service Principal to a VNET with

az role assignment create --assignee SP_CLIENT_ID --scope VNET_ID --role Contributor

Where can I review the configuration (Azure portal or cli)?

Update: I was looking for the subnets roles assignment which are a bit hidden under: vNet > Subnets > Managed users > Role assignments.

Yannick's user avatar

  • IAM blade under that specific vNet? We use service connections to deploy and configure all our resources and these service principals are being assigned a role and are visible under the IAM blade. –  LMG Commented May 4, 2020 at 22:42

2 Answers 2

1.Use Azure portal:

Navigate to the vnet in the portal -> Access control (IAM) -> Role assignments -> search for the name of your service principal like below.

enter image description here

2.Use Azure CLI:

enter image description here

  • Ah I see, the scope has to be absolute, I thought it would list child resources as well. –  Yannick Commented May 5, 2020 at 9:46
  • @Yannick yes, vnet and subnet have different resource ids. –  Joy Wang Commented May 5, 2020 at 10:41
  • 1 I get an empty list, weird –  Yannick Commented May 7, 2020 at 11:19
  • 1 @JoyWang, same here. –  Yash Mochi Commented Jul 1, 2022 at 10:39
  • 1 @Yannick I tried even setting subscription. Still getting empty list. –  Yash Mochi Commented Jul 1, 2022 at 10:40

For future readers, if you tried to use Joy's answer to query for all roles assigned to a Managed Identity, and you're unexpectedly receiving an empty array, try adding the --all switch.

EX: az role assignment list --assignee '<PRINCIPAL_ID>' --all

The relevant docs are here .

derekbaker783's user avatar

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 azure-cli or ask your own question .

  • The Overflow Blog
  • How to build open source apps in a highly regulated industry
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Is anything implied by the author using the (Greek) phrase translated "work with your hands" in 1 Thessalonians 4:11?
  • How does this switch work on each press?
  • Is there a drawback to using Heart's blood rote repeatedly?
  • How to clean up interrupted edge loops using geometry nodes and fill holes with quad faces?
  • How far back in time have historians estimated the rate of economic growth and the economic power of various empires?
  • Powers of Gaussian primes are NOT collinear
  • Can you always extend an isometry of a subset of a Hilbert Space to the whole space?
  • How to maintain dependencies shared among microservices?
  • Inversion naming conventions
  • Do Christians believe that Jews and Muslims go to hell?
  • Books using the axiomatic method
  • Can someone explain the Trump immunity ruling?
  • Does concentrating on a different spell end a concentration spell?
  • Can you arrange 25 whole numbers (not necessarily all different) so that the sum of any three successive terms is even but the sum of all 25 is odd?
  • Could someone translate & explain the Mesorah?
  • How well does the following argument work as a counter towards unfalsifiable supernatural claims?
  • I want to leave my current job during probation but I don't want to tell the next interviewer I am currently working
  • Position where last x halfmoves are determined
  • Did the BBC censor a non-binary character in Transformers: EarthSpark?
  • Does the decision of North Korea sending engineering troops to the occupied territory in Ukraine leave them open to further UN sanctions?
  • Are there examples of triple entendres in English?
  • PWM Dimming of a Low-Voltage DC Incandescent Filament (Thermal Shock?)
  • What does a letter "R" means in a helipad?
  • A very basic autosegmental tree using forest

role assignment list

All about Microsoft 365

Generate a report of Azure AD role assignments via the Graph API or PowerShell

A while back, I published a short article and script to illustrate the process of obtaining a list of all Azure AD role assignments. The examples therein use the old MSOnline and Azure AD PowerShell modules, which are now on a deprecation path. Thus, it’s time to update the code to leverage the “latest and greatest”. Quotes are there for a reason…

The updated script comes in two flavors. The first one is based on direct web requests against the Graph API endpoints and uses application permissions, thus is suitable for automation scenarios. Do make sure to replace the authentication variables, which you can find on lines 11-13. Better yet, replace the whole authentication block (lines 7-36) with your preferred “connect to Graph” function. Also make sure that sufficient permissions are granted to the service principal under which you will be running the script. Those include the Directory.Read.All scope for fetching regular role assignments and performing directory-wide queries, and the RoleManagement.Read.Directory for PIM roles.

The second flavor is based on the cmdlets included as part of the Microsoft Graph SDK for PowerShell. As authentication is handled via the Connect-MGGraph cmdlet, the script is half the size of the first one. And it would’ve been even smaller were it not for few annoying bugs Microsoft is yet to address.

In all fairness, switching to the Graph does offer some improvements, such as being able to use a single call to list all role assignments. This is made possible thanks to the  /roleManagement/directory/roleAssignments endpoint (or calling the Get-MgRoleManagementDirectoryRoleAssignment cmdlet). Previously, we had to iterate over each admin role and list its members, which is not exactly optimal, and given the fact that the list of built-in roles has now grown to over 90, it does add up. On the negative side, we have a bunch of GUIDs in the output, most of which we will want to translate to human-readable values, as they designate the user, group or service principal to which a given role has been assigned, as well as the actual role. One way to go about this is to use the $expand operator (or the – ExpandProperty parameter if using the SDK) to request the full object.

While this is the quickest method, the lack of support for the $select operator inside an $expand query means we will be fetching a lot more data than what we need for the report. In addition, there seems to be an issue with the definition of the expandable properties for this specific endpoint, as trying to use the handy $expand=* value will result in an error ( “Could not find a property named ‘appScope’ on type ‘Microsoft.DirectoryServices.RoleAssignment'” ). In effect, to fetch both the expanded principal object and the expanded roleDefinition object, we need to run two separate queries and merge the results. Hopefully Microsoft will address this issue in the future (the /roleManagement/directory/roleEligibilitySchedules we will use to fetch PIM eligible role assignments does support $expand=* query).

Another option is to collect all the principalIDs and issue a POST request against the /directoryObjects/getByIds endpoint (or the corresponding Get-MgDirectoryObjectById cmdlet), which does have a proper support for $select . A single query can be used to “translate” up to 1000 principal values, which should be sufficient for most scenarios. With the information gathered from the query, we can construct a hash-table and use it to lookup the property values we want to expose in our report. Lastly, you can also query each principalID individually, but that’s the messiest option available.

Apart from role assignments obtained via the /roleManagement/directory/roleAssignments call, the script can also include any PIM eligible role assignments. To fetch those, invoke the script with the – IncludePIMEligibleAssignments switch. It will then call the /v1.0/roleManagement/directory/roleEligibilitySchedules endpoint, or similarly, use the Get-MgRoleManagementDirectoryRoleEligibilitySchedule cmdlet. Some minor adjustments are needed to ensure the output between the two is uniform, which includes the aforementioned issue with expanding the navigation properties. But hey, it wouldn’t be a Microsoft product if everything worked out of the box 🙂

Here are some examples on how to run the scripts. The first example uses the Graph API version and no parameters. For the second one, we invoke the – IncludePIMEligibleAssignments parameter in order to include PIM eligible role assignments as well. The last example does the same thing, but for the Graph SDK version of the script.

And with that, we’re ready to build the output. Thanks to the $expand operator and the workarounds used above, we should be able to present sufficient information about each role assignment, while minimizing the number of calls made. The output is automatically exported to a CSV in the script folder, and includes the following fields:

  • Principal – an identifier for the user, group or service principal to which the role has been assigned. Depending on the object type, an UPN, appID or GUID value will be presented.
  • PrincipalDisplayName – the display name for the principal.
  • PrincipalType – the object type of the principal.
  • AssignedRole – the display name of the role assigned.
  • AssignedRoleScope – the assignment scope, either the whole directory (“/”) or a specific administrative unit.
  • AssignmentType – the type of assignment (“Permanent” or “Eligible”).
  • IsBuiltIn – indicates whether the role is a default one, or custom-created one.
  • RoleTemplate – the GUID for the role template.

Now, it’s very important to understand that this script only covers Azure AD admin roles, either default or custom ones, and optionally eligible PIM-assignable roles (do note that the PIM cmdlets/endpoints do not cover all custom role scenarios). Apart from these, there are numerous workload-specific roles that can be granted across Office 365, such as the Exchange Online Roles and assignments, Roles in the Security and Compliance Center, site collection permissions in SharePoint Online, and so on. Just because a given user doesn’t appear in the admin role report, it doesn’t mean that he cannot have other permissions granted!

In addition, one should make sure to cover any applications (service principals) that have been granted permissions to execute operations against your tenant. Such permissions can range from being able to read directory data to full access to user’s messages and files, so it’s very important to keep track on them. We published an article  that can get you started with a sample script a while back.

9 thoughts on “ Generate a report of Azure AD role assignments via the Graph API or PowerShell ”

  • Pingback: Reporting on Entra ID directory role assignments (including PIM) - Blog

' src=

This script is very nicely written, however the output of the Powershell Graph SDK version is incorrect (I didn’t check the other).

If I am eligible to activate a role I’ll be in the eligible list. However once I activate the role, my activated role assignment will show up in the list of role assignments from “Get-MgRoleManagementDirectoryRoleAssignment”. The output of that command doesn’t include a ‘status’ property. Your script assumes that if there’s no ‘status’ then the assignment is permanent, however that’s not accurate. So every eligible user who has activated a role shows up twice in the output of your script – once as as eligible for the role and once as a permanent assignment.

I came across your script because I’m trying to accomplish a similar task. My goal is to enumerate all the users who have eligible or permanent role assignments. I think the answer may be that if a user is in the eligible list, and also in the role assignment list, for the same role, then you can assume that the role assignment came from activation, but that doesn’t really seem very satisfactory.

' src=

Thanks Matt. The script is a bit outdated by now, I don’t even know if it runs with the “V2” Graph SDK. I’ll update it at some point 🙂

To further address your comment – neither the Get-MgRoleManagementDirectoryRoleAssignment nor the Get-MgRoleManagementDirectoryRoleEligibilitySchedule cmdlet returns sufficient information in order to determine whether a given (eligible) role assignment is currently activated. You can get this information via Get-MgRoleManagementDirectoryRoleAssignmentScheduleInstance, should be easy enough to add to the next iteration of the script.

' src=

Hi, thks for your great work. do you know why i dont see the eligible assignements ?

Seems they made some changes and you can no longer use $expand=* on the /v1.0 endpoint. Try using /beta, should work there. I’ll update the script when I get some time.

I’ve updated the script, let me know if you are still having issues.

' src=

Awesome, thank you very much.

' src=

Merci merci merci !!! Thanks thanks thanks !!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Gain insights into your Azure role assignments on subscription level

Gain insights into your Azure role assignments on subscription level

List Azure role assignments and custom role definitions recursively with PowerShell and Azure CLI.

Jump to recipe

Azure Role-Based Access Control (RBAC)

Azure role-based access control (Azure RBAC) helps you manage who has access to Azure resources, what they can do with those resources, and what areas they have access to. Using RBAC in Azure for granular permissions makes it easy to assign permissions to users, groups, service principals, or managed identities. You can assign only the amount of access that users need to perform their jobs, thereby adhering to the principle of least privilege.

You have a ton of builtin roles to choose from, and you can also create your own custom roles if none of the builtin roles fit your use case.

I will not write a thesis on Azure RBAC, as you can find the necessary information on the Azure RBAC documentation page . I will, however, highlight a few shortcomings and how I worked around some of them.

List Azure role definitions

You can list role definitions in the portal , with Azure CLI , or PowerShell .

All these links read List all roles . That is a bit misleading, as they only list the roles in your current scope with any inherited from above (management groups). Any custom roles created in different subscriptions than the current one (or the one provided in scope parameter) will not be listed. A best practice is to create custom roles higher up in management groups so that they are inherited by all subscriptions below. This is not always done, and you might end up with custom roles in different subscriptions.

List Azure role assignments

You can list role assignments in the portal , with PowerShell , or with Azure CLI . There are different ways of listing role assignments, but no way to list all role assignments in your hierarchy recursively. You can list role assignments at a certain scope, with inherited assignments included. You can also find all role assignments for a specific user or group in Azure AD .

Shortcomings

As far as I can see, there are a few shortcomings. These are not critical, and there are other issues with the RBAC model, but I will not go into them here.

  • There is no central listing of role assignments for all scopes
  • There is no central listing of custom role definitions for all scopes
  • Role assignments and role definitions are not linked in any way other than in backend. If you try to delete a custom role definition still in use, you get an error message. You have to find all role assignments using the custom role definition and delete them first.
  • Role assignments and role definitions are not listed in Azure AD

Recently I was tasked with cleaning some clickOps’ed custom role definitions and converting them to Terraform. I needed to find all custom role definitions and all role assignments in all subscriptions in all management groups. I also needed to find all role assignments using the custom role definitions I was going to delete. Because of reasons I needed to create new role definitions, and could not import them into Terraform. Because of the shortcomings mentioned above, I had to write a script to list all role definitions and role assignments for all scopes.

I did not want to click through all of the subscriptions and management groups, so I wrote a script to do it for me.

Azure Governance Visualizer

At this point I would be remiss not to mention the Azure Governance Visualizer . It is a great tool created by Julian Hayward for visualizing your total Azure Governance. It lists all custom role definitions and every other detail you would need from your environment regarding RBAC and lot of other useful information. In this case it is too complex, and I wanted to focus on the RBAC part. Anyway, check it out if you need a great tool for visualizing your Azure Governance.

Log in with both Azure CLI and PowerShell

Recursively find all management groups and subscriptions, list all custom roles in all subscriptions, list all role assignments with relevant custom roles in all subscriptions, write everything to json files for documentation or investigation, prerequisites.

  • A user with Reader role on the management group level to list all management groups.
  • A user with Reader role on the subscription level to list all subscriptions and their assignments/definitions.
  • Azure PowerShell installed
  • Azure CLI installed

The script can be found in all its glory in GitHub . I will explain the different sections below.

I did not want the script to force a login of both PowerShell and Azure CLI every time I ran it. Therefore I needed some logic to check for login status and login if necessary.

Since there could be several management groups in different levels, I need to recursively find the management groups to list all subscriptions.

This part is a simple loop through all subscriptions and list all custom role definitions. I could have used the PowerShell cmdlet Get-AzRoleDefinition , but I wanted to use the Azure CLI command az role definition list to get some more relevant information. The other actions done for each subscription are also done in the same foreach loop.

This part is a simple loop through all custom roles in the current subscription and list all assignments. Exports them if required with exportAssignments parameter.

This part is a simple conversion from PowerShell objects to json with ConvertTo-Json and dumpt to json file.

  • Azure PowerShell

Some parameters are necessary in this script to make it dynamic.

  • topLvlMgmtGroup - [String] Id of your top level management group to start recursive listing.
  • customRolesOnly - [String] Set to true if exporting only custom roles. Defaults to true .
  • excludeRegexPattern - [String] Any exclusion RegEx pattern to use. Remember escape chars!
  • rolesFolder - [String] Folder where role definitions will be exported. Defaults to output .
  • exportAssignments - [Switch] Whether to export assignments to file or not.
  • subscription - [String] Subscription Id or name for when exporting in a single subscription.

Resulting json

Running the script results in some output to json files.

Role Definitions

It makes sense to only export custom role definitions, because the builtin ones are already pretty well documented.

For each custom role definition found, one file will be written. This is an example role and all guids are randomly generated.

Role Assignments

All role assignments will be exported if the relevant parameter is set.

Output to a single assignments.json:

I had some fun with this task, and maybe created an over engineered solution. Also I had the chance to practice my PowerShell-skills, which is a welcomed exercise!

Please let me know if you have a one-liner for this that I can use in the future 🙂

  • Google Workspace
  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt
  • Admin console

Method: roleAssignments.list

Retrieves a paginated list of all roleAssignments.

HTTP request

GET https://admin.googleapis.com/admin/directory/v1/customer/{customer}/roleassignments

The URL uses gRPC Transcoding syntax.

Path parameters

Parameters

The unique ID for the customer's Google Workspace account. In case of a multi-domain account, to fetch all groups for a customer, use this field instead of . You can also use the alias to represent your account's . The is also returned as part of the resource. You must provide either the or the parameter.

Query parameters

Parameters

Maximum number of results to return.

Token to specify the next page in the list.

Immutable ID of a role. If included in the request, returns only role assignments containing this role ID.

The primary email address, alias email address, or unique user or group ID. If included in the request, returns role assignments only for this user or group.

When set to , fetches indirect role assignments (i.e. role assignment via a group) as well as direct ones. Defaults to . You must specify or the indirect role assignments will not be included.

Request body

The request body must be empty.

Response body

If successful, the response body contains data with the following structure:

JSON representation
"kind": string, "etag": string, "items": [ { object ( ) } ], "nextPageToken": string }
Fields

The type of the API resource. This is always .

ETag of the resource.

)

A list of RoleAssignment resources.

Authorization scopes

Requires one of the following OAuth scopes:

  • https://www.googleapis.com/auth/admin.directory.rolemanagement
  • https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly

For more information, see the Authorization guide .

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-05-15 UTC.

  • Manage projects, users, and roles

Manage projects, users, and roles ¶

As an administrator, you manage projects, users, and roles. Projects are organizational units in the cloud to which you can assign users. Projects are also known as projects or accounts . Users can be members of one or more projects. Roles define which actions users can perform. You assign roles to user-project pairs.

You can define actions for OpenStack service roles in the /etc/PROJECT/policy.json files. For example, define actions for Compute service roles in the /etc/nova/policy.json file.

You can manage projects, users, and roles independently from each other.

During cloud set up, the operator defines at least one project, user, and role.

You can add, update, and delete projects and users, assign users to one or more projects, and change or remove the assignment. To enable or temporarily disable a project or user, update that project or user. You can also change quotas at the project level.

Before you can delete a user account, you must remove the user account from its primary project.

Before you can run client commands, you must download and source an OpenStack RC file. See Download and source the OpenStack RC file .

A project is a group of zero or more users. In Compute, a project owns virtual machines. In Object Storage, a project owns containers. Users can be associated with more than one project. Each project and user pairing can have a role associated with it.

List projects ¶

List all projects with their ID, name, and whether they are enabled or disabled:

Create a project ¶

Create a project named new-project :

Update a project ¶

Specify the project ID to update a project. You can update the name, description, and enabled status of a project.

To temporarily disable a project:

To enable a disabled project:

To update the name of a project:

To verify your changes, show information for the updated project:

Delete a project ¶

Specify the project ID to delete a project:

List users ¶

List all users:

Create a user ¶

To create a user, you must specify a name. Optionally, you can specify a project ID, password, and email address. It is recommended that you include the project ID and password because the user cannot log in to the dashboard without this information.

Create the new-user user:

Update a user ¶

You can update the name, email address, and enabled status for a user.

To temporarily disable a user account:

If you disable a user account, the user cannot log in to the dashboard. However, data for the user account is maintained, so you can enable the user at any time.

To enable a disabled user account:

To change the name and description for a user account:

Delete a user ¶

Delete a specified user account:

Roles and role assignments ¶

List available roles ¶.

List the available roles:

Create a role ¶

Users can be members of multiple projects. To assign users to multiple projects, define a role and assign that role to a user-project pair.

Create the new-role role:

If you are using identity v3, you may need to use the --domain option with a specific domain name.

Assign a role ¶

To assign a user to a project, you must assign the role to a user-project pair. To do this, you need the user, role, and project IDs.

List users and note the user ID you want to assign to the role:

List role IDs and note the role ID you want to assign:

List projects and note the project ID you want to assign to the role:

Assign a role to a user-project pair:

For example, assign the new-role role to the demo and test-project pair:

Verify the role assignment:

Before the Newton release, users would run the openstack role list --user USER_NAME --project TENANT_ID command to verify the role assignment.

View role details ¶

View details for a specified role:

Remove a role ¶

Remove a role from a user-project pair:

Run the openstack role remove command:

Verify the role removal:

If the role was removed, the command output omits the removed role.

Creative Commons Attribution 3.0 License

Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License . See all OpenStack Legal Documents .

  • Install Guides
  • User Guides
  • Configuration Guides
  • Operations and Administration Guides
  • Contributor Guides
  • Deutsch (German)
  • Français (French)
  • Bahasa Indonesia (Indonesian)
  • Italiano (Italian)
  • 日本語 (Japanese)
  • 한국어 (Korean)
  • Português (Portuguese)
  • Türkçe (Türkiye)
  • 简体中文 (Simplified Chinese)

keystone 12.0.4.dev11

  • Keystone Installation Tutorial
  • Getting Started
  • Code Documentation
  • Indices and tables
  • Contributor Documentation
  • Configuring Keystone
  • Advanced Topics
  • User Documentation
  • CLI Documentation
  • Identity concepts
  • Bootstrapping Identity
  • Create and manage services and service users
  • Certificates for PKI
  • Domain-specific configuration
  • URL safe naming of projects and domains
  • External authentication with Identity
  • Integrate Identity with LDAP
  • Upgrading Keystone
  • Keystone tokens
  • Configure Identity service for token binding
  • Fernet - Frequently Asked Questions
  • Caching layer
  • Security compliance and PCI-DSS
  • Performance and scaling
  • Example usage and Identity features
  • Authentication middleware with user name and password
  • Identity API protection with role-based access control (RBAC)
  • Troubleshoot the Identity service
  • Token provider
  • Federated Identity
  • Credential Encryption
  • Keystone Configuration Options

Page Contents

  • List projects
  • Create a project
  • Update a project
  • Delete a project
  • Create a user
  • Update a user
  • Delete a user
  • List available roles
  • Create a role
  • Assign a role
  • View role details
  • Remove a role

Working Man's SharePoint

Managing Role Assignments/Permissions with SharePoint REST

To assign permissions in SharePoint, you make one or more role assignments, which requires three things:

  • Some kind of handle for a securable object. That’s basically a site, list, library, folder, document, or item.
  • The principal id for something to which roles can be assigned. That’s either an Active Directory user or security group, or a SharePoint group.
  • The id of a role definition. Like ‘Full Control’ or ‘Edit’ or ‘Contribute’. This is basically a named collection of granular permissions that are defined at the site collection root and can be assigned to a securable object in that site collection.

In this post, I’m going to explain the REST service calls required in order to make role assignments to SharePoint securable objects. I will show the calls using jQuery’s ajax (because I’m working through them in the console and the console won’t resolve promises). I’ll follow up with a post with some demo code pulling it all together and probably using fetch.

Role Assignments: Prerequisites

As explained above, there are three things I need to make a role assignment, and while these aren’t directly related to role assignments, this is a series on REST in general so I’m going to explain all of the service calls.

The first thing I will get is collection of lists that are available in the current site, via the endpoint /_api/web/lists . Now this endpoint basically returns the whole list schema, and I don’t need all of that, so to reduce the payload I’ll add $select=Id,Title as a request parameter. I also want to weed out hidden lists, so I’ll add $filter=Hidden eq false . With that, the call looks like:

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists?$select=Id,Title&$filter=Hidden eq false"; .ajax({ url: url, type: 'GET', headers: { 'accept': 'application/json;odata=nometadata' }, success: function(data) { console.log(data); }, error: function(error) { console.log(error); } );

And the returned JSON structure looks like this:

= { value: [ { Id: "6cf00975-3daa-4510-bc93-6c4f8be8da7f", Title: "JobTitles" }, { Id: "ad9fccd3-93ef-4c56-8d97-85a3179397ad", Title: "Pictures" }, { Id: "7127dc6e-739a-4b28-a8f6-2d140838c11a", Title: "Promoted Links" }, { Id: "5286bc76-8239-468b-81a1-befcb4499e67", Title: "SalesDivision" }, { Id: "7c72b15c-8dac-4528-9544-f72e4b6329e3", Title: "SalesRegion" }, { Id: "54bff8cc-6585-4890-9870-3b5b5e64ba6a", Title: "SalesState" }, { Id: "86a21b2e-326c-4ec2-af53-a5004fdb09d8", Title: "Shared Documents" }, { Id: "444442b4-6560-4716-8b7e-b70f16b2915c", Title: "Speaker Evaluations" } ]

I’ll use this data to populate some sort of multi-select control for lists and can then get a handle on each list by either id or title.

Site Groups

Next, I’ll need to populate a drop-down list with site collection groups. Again, I’ll add the request parameter $select=Id,Title , and while with lists I could have gotten away with just title, here I need both because add role assignment requires the id, and users are likely going to need the title. Here’s the call:

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups?$select=Id,Title"; .ajax({ url: url, type: 'GET', headers: { 'accept': 'application/json;odata=nometadata' }, success: function(data) { console.log(data); }, error: function(error) { console.log(error); } );

And the response JSON structure looks like this:

= { value: [{ Id: 9, Title: "CSRDemos Members" }, { Id: 7, Title: "CSRDemos Owners" }, { Id: 8, Title: "CSRDemos Visitors" }, { Id: 3, Title: "Excel Services Viewers" } ] ;

I’m not actually going to need this in the demo page, but to be thorough, if you know the name of the group, you can get it’s ID with this call (a lot less chatty):

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getbyname('Excel Services Viewers')/id"; .ajax({ url: url, type: 'GET', headers: { 'accept': 'application/json;odata=nometadata' }, success: function(data) { console.log(data); }, error: function(error) { console.log(error); } );

And the response from this call is quite succinct:

= { value: 3 ;

Role Definitions

And the final preliminary piece of the puzzle is that I need a role definition id. To get a list of role definitions defined in the site collection, I make the following call:

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/roledefinitions"; .ajax({ url: url, type: 'GET', headers: { 'accept': 'application/json;odata=nometadata' }, success: function(data) { console.log(data); }, error: function(error) { console.log(error); } );

Now I didn’t actually select anything, so I’m getting back more information than I actually need, but it’s not that big a structure and I wanted to show the whole thing. In particular, note the base permissions structure. I talked about this a bit in my last post Determining the Permissions of the Current User with REST , and how to dissect this structure to get the granular access controls it represents. Anyway, here is the complete JSON structure returned from the role definitions endpoint.

= { value: [{ BasePermissions: { High: "2147483647", Low: "4294967295" }, Description: "Has full control.", Hidden: false, Id: 1073741829, Name: "Full Control", Order: 1, RoleTypeKind: 5 }, { BasePermissions: { High: "432", Low: "1012866047" }, Description: "Can view, add, update, delete, approve, and customize.", Hidden: false, Id: 1073741828, Name: "Design", Order: 32, RoleTypeKind: 4 }, { BasePermissions: { High: "432", Low: "1011030767" }, Description: "Can add, edit and delete lists; can view, add, update and delete list items and documents.", Hidden: false, Id: 1073741830, Name: "Edit", Order: 48, RoleTypeKind: 6 } ]

The only things I actually need from this are the name and the id.

If you know the name of the role definition you’re interested in, you can get the id with the following REST call:

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/roledefinitions/getbyname('Edit')/id"; .ajax({ url: url, type: 'GET', headers: { 'accept': 'application/json;odata=nometadata' }, success: function(data) { console.log(data); }, error: function(error) { console.log(error); } );

And the very simple returned JSON structure from this call looks like:

= { value: 1073741830 ;

Manipulating Role Assignments

Whew! We finally have enough information to make a role assignment. It’s a bit tedious, but not that hard (which kind of describes programming in general). In the following code, I’m going to work on the permissions of the list titled “Speaker Evaluations” . And prior to doing anything, the permissions for that list look like this:

Initial Role Assignments

The first thing I need to do is check if the list is currently inheriting permissions. To do that, just like object model code, I need to call has unique role assignments like so:

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Speaker Evaluations')/hasuniqueroleassignments"; .ajax({ url: url, type: 'GET', headers: { 'accept': 'application/json;odata=nometadata' }, success: function(data) { console.log(data); }, error: function(error) { console.log(error); } );

Keep in mind that the part of the URL before /hasuniqueroleassignments is what I called earlier “a handle to a securable object”, in this case, a list. So I could just as easily use /_api/web/hasuniqueroleassignements , and the returned value would be in exactly the same format but would have told me if the web had broken inheritance. And I could do …/items(2)/hasuniqueroleassignments to determine if the item with id 2 has broken role inheritance. The same is true of all of the endpoints to follow in this post, they can all be tacked onto any URL that represents a securable object to perform securable operations on those objects.

Anyway, here is the returned value, which would be true if role inheritance had already been broken:

= { value: false ;

If the list is currently inheriting permissions, I now need to break role inheritance. I do that with the following call, passing in false. The input is true if I want to copy all of the role assignments from the parent and false if I want to start with a blank slate.

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Speaker Evaluations')/breakroleinheritance(false)"; .ajax({ url: url, type: 'POST', headers: { 'accept': 'application/json;odata=nometadata', 'X-RequestDigest': $('#__REQUESTDIGEST').val() }, success: function(data) { console.log(data); }, error: function(error) { console.log(error); } );

Which returns the terribly useful JSON structure shown below. Basically, if success gets called back, that’s enough to shout WOO HOO!

= { "odata.null": true

And if I re-check the permissions for my list it now looks like this:

Broken Inheritance

Yours will look a little different of course. I wouldn’t expect you to see permissions assigned to Joe McShea for instance ;). Breaking role inheritance with false just assigns full control to the current user to prevent orphaned objects.

But calling break role inheritance on an object that already doesn’t inherit does nothing. Even if you pass in false, it certainly doesn’t delete any previously copied role assignments from the parent. That’s why I had to check has unique role assignments, because if not then I call the above service, and if so then I call the following service.

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Speaker Evaluations')/roleassignments/getbyprincipalid('9')"; .ajax({ url: url, type: 'POST', headers: { 'accept': 'application/json;odata=nometadata', 'X-RequestDigest': $('#__REQUESTDIGEST').val(), 'X-HTTP-Method': 'DELETE' }, success: function(data) { console.log("'" + data + "'"); }, error: function(error) { console.log(error); } );

This call just deletes all role assignments for the user I’m about to add role assignments for. That way, at least with respect to this one user, I always start with a clean slate. Curiously, this call returns nothing on success, just a blank string. not even a lousy { “object.null” : true } ! One thing you need to know, however, is if the user has no role assignments, the result is a “404 Not Found”. This isn’t an error. You asked for a resource and it wasn’t found. So you should handle 404 errors as appropriate.

= ''

And finally, we’ve arrived at the point of this post, which is making a role assignment. The following service call adds a role assignment to the “Speaker Evaluation” list, which assigns Edit (i.e. roledefid=’1073741830′) to the SharePoint group “CSRDemos Members” (i.e. principalid=’9′).

= _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Speaker Evaluations')/roleassignments/addroleassignment(principalid='9',roledefid='1073741830')"; .ajax({ url: url, type: 'POST', headers: { 'accept': 'application/json;odata=nometadata', 'X-RequestDigest': $('#__REQUESTDIGEST').val() }, success: function(data) { console.log(data); }, error: function(error) { console.log(error); } );

And again we see this very useful structure. But again, the fact that the success callback was called is more than enough.

And now if I check the permissions for the list, I see:

Added Role Assignment

In this post I showed the various pieces you need to navigate in order to assign roles to SharePoint groups using the REST API. In my next post, I’ll pull it all together with a demo page.

Set custom permissions on a list by using the REST interface – Microsoft Docs

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Pocket (Opens in new window)

4 thoughts on “Managing Role Assignments/Permissions with SharePoint REST”

I am facing issue with ‘X-RequestDigest’: $(‘#__REQUESTDIGEST’).val(). what is mean by ‘X-RequestDigest’: $(‘#__REQUESTDIGEST’).val() in header

So SharePoint Pages generally have a hidden control with an id of __REQUESTDIGEST . If you view source on a SharePoint page and search for that ID, you should see the control. It’s just some kind of hash, that you have to send back to the server in the X-RequestDigest header in order to do any write operations (i.e. POST, PUT, MERGE, or DELETE), if you’re not using OAuth .

JavaScript that runs on a SharePoint page doesn’t need to do OAuth since the user has already authenticated in the browser, so it can just use the __REQUESTDIGEST value of the current page like I am.

$("#__REQESTDIGEST").val() is using jQuery to get that digest value. Without jQuery, you can use pure JavaScript something like document.getElementById("__REQUESTDIGEST").value . If document.getElementById("__REQUESTDIGEST") returns undefined then you’re either not on a SharePoint page, or the page doesn’t use a request digest.

And if you’re on a SharePoint page, meaning the user has already authenticated to SharePoint, but the page doesn’t have a control with an ID of __REQUESTDIGEST , then there is another way to get the request digest, which is to call the context info REST service to retrieve the digest, with a url like:

http://[site url]/_api/contextinfo

The digest serves a couple of purposes, including making sure your version of the item isn’t stale, so it expires from time to time (I believe 30 minutes by default). So if you try to use a stale digest, you’ll get an error like “An error has occurred with XXXX. Please refresh the page and try again”. In which case, you can use the context info service to refresh the digest.

Now if you’re not on a SharePoint page, then you probably have to use OAuth and worry about CORS (Cross Origin Resource Sharing), which is a whole different can of worms, and not what my post is about.

You can find a lot more info about this here:

Complete basic operations using SharePoint REST endpoints

That page has some information on the different contexts you might be in, like on a SharePoint page vs. using OAuth etc.

Hope that helps some.

First of all, thank you for this post, it’s very helpful.

I’d like to ask you if you know how to remove an external user from a specific folder/file.

I granted access to a folder with the “SP.Web.ShareObject” rest call method which accepts a “peoplePickerInput” body parameter (where you can define all the email addresses to invite), but the method “SP.Web.UnshareObject” only accepts the url parameter of the folder, so every external user will lose the access, which it’s not what I need.

Do you have any solution for this ? Thanks in advance.

I do not have any particular insight on that, but I’ll take a look when I get a chance, and let you know if I figure it out.

Leave a Comment Cancel reply

You must be logged in to post a comment.

Get the Reddit app

Join us in discord here: https://aka.ms/azurediscord.

Azure RBAC Role assignment and permissions audit

Hello Folks,

In our Azure infrastructure, we have RBAC permissions set on the management group level, subscription level and resource group level; each having different RBAC and role assignments.

We are trying to build a heirarchical tree view of all role assignments that represents all role assignments, role definitions and the RBAC inheritence.

Is there a method. script or open source tool could be used to perform this extract ? We have tried using Scoutsuite but the tool only extracts the role definitions and not the role assignments. The other options we have considered is using powershell (Get-AzRoleAssignment -Scope <SCOPE>).

Many thanks in advance.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

List unifiedRoleAssignments

  • 15 contributors

Namespace: microsoft.graph

Get a list of unifiedRoleAssignment objects for the RBAC provider.

The following RBAC providers are currently supported:

  • directory (Microsoft Entra ID)
  • entitlement management (Microsoft Entra entitlement management)

This API is available in the following national cloud deployments .

Global service US Government L4 US Government L5 (DOD) China operated by 21Vianet

Permissions

One of the following permissions is required to call this API. To learn more, including how to choose permissions, see Permissions .

For the directory (Microsoft Entra ID) provider

Permission type Permissions (from least to most privileged)
Delegated (work or school account) RoleManagement.Read.Directory, RoleManagement.Read.All, Directory.Read.All, RoleManagement.ReadWrite.Directory, Directory.ReadWrite.All
Delegated (personal Microsoft account) Not supported.
Application RoleManagement.Read.Directory, RoleManagement.Read.All, Directory.Read.All, RoleManagement.ReadWrite.Directory, Directory.ReadWrite.All

For the entitlement management provider

Permission type Permissions (from least to most privileged)
Delegated (work or school account) EntitlementManagement.Read.All, EntitlementManagement.ReadWrite.All
Delegated (personal Microsoft account) Not supported.
Application EntitlementManagement.Read.All, EntitlementManagement.ReadWrite.All

HTTP request

To list role assignments for the directory provider:

To list role assignments for the entitlement management provider:

Optional query parameters

This method supports the $filter , $expand , and $select OData query parameters to help customize the response.

Request headers

Name Description
Authorization Bearer {token}. Required. Learn more about .

Request body

Don't supply a request body for this method.

If successful, this method returns a 200 OK response code and a collection of unifiedRoleAssignment objects in the response body.

Example 1: Request using a filter on roleDefinitionId and expand the principal object

The following example shows a request.

For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .

The following example shows the response.

Note: The response object shown here might be shortened for readability.

Example 2: Request using a filter on principalId

Example 3: request using $filter for role assignments on an access package catalog and expand the principal object.

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

IMAGES

  1. List Azure role assignments using the Azure portal

    role assignment list

  2. Role and Responsibilities Chart Templates

    role assignment list

  3. List Azure role assignments using the Azure portal

    role assignment list

  4. List Azure AD role assignments

    role assignment list

  5. Teams Role And Responsibility Assignment With Pictures Infographic

    role assignment list

  6. 12 RACI Matrix Presentation Charts Templates with Project

    role assignment list

VIDEO

  1. 22 Indirect Role Assignment

  2. ROLE PLAY GROUP ASSIGNMENT BA21103 INTERNATIONAL MARKETING

  3. Assignment role play disgruntle dinner situation 1

  4. HFT20103 ORGANIZATIONAL BEHAVIOUR

  5. ROLE PLAY ASSIGNMENT DUE30022 COMMUNICATIVE ENGLISH 2

  6. MFT 612 Case Assignment Role Play

COMMENTS

  1. List Azure role assignments using Azure CLI

    az role assignment list --assignee {assignee} By default, only role assignments for the current subscription will be displayed. To view role assignments for the current subscription and below, add the --all parameter. To include role assignments at parent scopes, add the --include-inherited parameter. To include role assignments for groups of which the user is a member transitively, add the ...

  2. az role assignment

    az role assignment list: List role assignments. Core GA az role assignment list-changelogs: List changelogs for role assignments. Core GA az role assignment update: Update an existing role assignment for a user, group, or service principal. Core GA

  3. List Azure role assignments using the Azure portal

    A quick way to see the roles assigned to a user or group in a subscription is to use the Azure role assignments pane. In the Azure portal, select All services from the Azure portal menu. Select Microsoft Entra ID and then select Users or Groups. Click the user or group you want list the role assignments for. Click Azure role assignments.

  4. Manage Azure Role Assignments Like a Pro with PowerShell

    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.

  5. role-assignments-list-rest.md

    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. Start with the following request:

  6. role-assignments-cli.md

    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.

  7. How to find all the Azure Built-In Roles for Azure RBAC with Azure CLI

    Here are a bunch of ways you can find which roles are built into Azure. This will come in super handy when you need to assign a role to a service principal or user with Azure CLI commands like this: az role assignment create --assignee 3db3ad97-06be-4c28-aa96-f1bac93aeed3 --role "Azure Maps Data Reader" Azure CLI. Query the big honking json

  8. A Beginner's Guide To Role-Based Access Control on Azure

    The way you control access to resources using RBAC is to create role assignments. This is a key concept to understand - it's how permissions are enforced. A role assignment consists of three elements: security principal, role definition, and scope. User - An individual who has a profile in Azure Active Directory.

  9. Where are the az role assignments listed

    For future readers, if you tried to use Joy's answer to query for all roles assigned to a Managed Identity, and you're unexpectedly receiving an empty array, try adding the --all switch. EX: az role assignment list --assignee '<PRINCIPAL_ID>' --all. The relevant docs are here.

  10. List Azure role assignments using the REST API

    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.

  11. Generate a report of Azure AD role assignments via the Graph API or

    A while back, I published a short article and script to illustrate the process of obtaining a list of all Azure AD role assignments. The examples therein use the old MSOnline and Azure AD PowerShell modules, which are now on a deprecation path. Thus, it's time to update the code to leverage the "latest and greatest".

  12. codewithme.cloud

    List Azure role assignments. You can list role assignments in the portal, with PowerShell, or with Azure CLI. There are different ways of listing role assignments, but no way to list all role assignments in your hierarchy recursively. You can list role assignments at a certain scope, with inherited assignments included.

  13. Understand Azure role assignments

    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 ...

  14. Method: roleAssignments.list

    Token to specify the next page in the list. roleId: string. Immutable ID of a role. If included in the request, returns only role assignments containing this role ID. userKey: string. The primary email address, alias email address, or unique user or group ID. If included in the request, returns role assignments only for this user or group.

  15. OpenStack Docs: Manage projects, users, and roles

    As an administrator, you manage projects, users, and roles. Projects are organizational units in the cloud to which you can assign users. Projects are also known as projects or accounts. Users can be members of one or more projects. Roles define which actions users can perform. You assign roles to user-project pairs.

  16. Managing Role Assignments/Permissions with SharePoint REST

    To assign permissions in SharePoint, you make one or more role assignments, which requires three things: Some kind of handle for a securable object. That's basically a site, list, library, folder, document, or item. The principal id for something to which roles can be assigned. That's either an Active Directory user or security group, or a ...

  17. Role Assignments

    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 a resource ...

  18. Azure RBAC Role assignment and permissions audit : r/AZURE

    In our Azure infrastructure, we have RBAC permissions set on the management group level, subscription level and resource group level; each having different RBAC and role assignments. We are trying to build a heirarchical tree view of all role assignments that represents all role assignments, role definitions and the RBAC inheritence.

  19. List unifiedRoleAssignments

    Namespace: microsoft.graph. Get a list of unifiedRoleAssignment objects for the RBAC provider. The following RBAC providers are currently supported: directory (Microsoft Entra ID) entitlement management (Microsoft Entra entitlement management) This API is available in the following national cloud deployments. Expand table.