This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Role Assignments - Create
Create or update a role assignment by scope and name.
URI Parameters
Request body, permissions.
To call this API, you must be assigned a role that has the following permissions. For more information, see Azure built-in roles .
Microsoft.Authorization/roleAssignments/write
Azure Active Directory OAuth2 Flow
Type: oauth2 Flow: implicit Authorization URL: https://login.microsoftonline.com/common/oauth2/authorize
Create role assignment for resource
Sample request.
To use the Azure SDK library in your project, see this documentation . To provide feedback on this code sample, open a GitHub issue
Sample Response
Create role assignment for resource group, create role assignment for subscription, definitions, error additional info.
The resource management error additional info.
Error Detail
The error detail.
Error Response
Error response
Principal Type
The principal type of the assigned principal ID.
Role Assignment
Role Assignments
Role Assignment Create Parameters
Role assignment create parameters.
Additional resources
- GenAI Innovation Center
- Consultancy and Migration
- Contract Staffing
- Data Analytics
- DevOps and DevSecOps
- Managed Services
- Media Services
- Generative AI with AWS
- AI, ML & IOT
- Cloud Native
- Containerization
- Well Architected Review
- Well Architected Infrastructure
- AWS Know Your Architecture
- Migration Services
- DevOps Services
- AWS Microsoft Workloads
- AWS Machine Learning
- AWS Storage
- AWS Security
- Amazon QuickSight
- Amazon API Gateway
- Amazon DynamoDB
- Amazon Redshift
- AWS Control Tower
- Observability With AWS
- GenAI STACQ
- Smart Document Search with GenAI
- Intelligent Document Processing
- Real-time Customer Call Analysis
- SmartMail Solution
- Corporate Training
- Training for Myself
- Azure Mastey Pass
- AWS Mastery Pass
- DevOps Mastery Pass
- Microsoft Dynamics Mastery Pass
- Microsoft Security Mastery Pass
- Power Platform Mastery Pass
- Job Guarantee Program
- Training Calendar
- Hire From Us
About CloudThat
- Join Our Team
- News and Event
Azure, Cloud Computing
Simplified Role Management: Azure REST API for User and App Registration Roles
- By Sridhar Andavarapu
Introduction
In modern cloud computing, managing access and permissions to resources is crucial to maintaining security and governance in Azure. To programmatically manage RBAC roles and permissions, developers can leverage the power of Azure’s REST API. Before using APIs to create and assign the custom roles to users or principals present in Azure subscription, do the below 2 steps for granting the permissions to the App Registration.
- Whether App Registration has been assigned with a role having necessary authorization permissions to that same subscription or not, as this will be using the Secret Value (part of the four required IDs) in the REST API that generates from the App Registration itself. (Steps detailed below)
- Check whether Authorization service resource provider is registered or not. If not registered, we need to register it on the Subscription Page, as shown below.
Assign the Custom RBAC Role to the Principal ID of App Registration
Follow the below steps to assign the custom RBAC role to App Registration in the portal.
- Go To Subscription Resource -> Click on IAM in the left panel -> Click on Add custom role as below.
2. After clicking Add custom role, it will be redirected to a new page for creating a custom role. Give a sample role name in Basics Tab -> go to the Permissions Tab -> click on Add Permissions -> search for Authorization permission -> Select all below permissions as shown in the below image.
3. Click on Review+Create. So custom role will get created in the category of custom role.
4. Now, Assign the newly created custom RBAC role to the principal id of App Registration.
Click on Add role assignment.
5. Search for the custom role created in step 3 -> click Next.
6. Go to the Members Tab -> Click on Select members -> Now search for the App Registration name in the search bar for which we wanted to assign the custom role. -> click on Select -> Click on Review + assign .
Pioneers in Cloud Consulting & Migration Services
- Reduced infrastructural costs
- Accelerated application deployment
Steps to Check the Service Based Resource Providers Registered
Go to Subscriptions -> Click on Resource Providers in the Left Panel -> Check Microsoft.Authorization is Registered or not.
Generate Bearer Token Using Tenant ID, Client ID & Secret Value
- https://login.microsoftonline.com/<tenant id>/oauth2/token
- Paste the above URL with the Tenant ID in Postman Application
- Go to Body -> select x-www-form-urlencoded and provide the below body as Key and Value pair
Ex: Provide grant_type as Key and client_credentials as Value
4. The above API request will respond in JSON format, passing the value of the access_token key as a bearer token in all the REST API operations.
Create the Custom Role Using Azure REST API
- Use the REST API below to create the custom role, replace the value of the subscription ID and use the PUT
https://management.azure.com/subscriptions/{ subscriptionId }/providers/Microsoft.Authorization/roleDefinitions/ {UUID} ?api-version=2022-04-01
- Use the link below to generate a new UUID, use the same API, and request body value.
Online UUID Generator Tool
- Go to Headers and provide the data below as key and value pair.
- Provide the sample API Request body below in the Body -> select raw .
Now, click on Send in the same request and get an appropriate response with the same rolename as the sample response below.
Assign the Custom Role to Principal ID Using Azure REST API
- Use the REST API below to assign the user’s custom role, replace the value of the subscription ID and use the PUT
https://management.azure.com/subscriptions/ {subscriptionID} /providers/Microsoft.Authorization/roleAssignments/ {UUID} ?api-version=2022-04-01
- Use the link below to generate one newer UUID, use the same value in the above API, and use the UUID of created custom role for which we have used to create the role and pass the same in the request body.
- Use the object ID of any user in an organization or tenant level and replace it with the UserID for whom you will assign this created custom role in the previous step.
- Now, click Send in the same request and get an appropriate response with the same rolename as shown below.
Drop a query if you have any questions regarding Azure REST API and we will get back to you quickly.
Making IT Networks Enterprise-ready – Cloud Management Services
- Accelerated cloud migration
- End-to-end view of the cloud environment
CloudThat is an official AWS (Amazon Web Services) Advanced Consulting Partner and Training partner and Microsoft Gold Partner, helping people develop knowledge of the cloud and help their businesses aim for higher goals using best in industry cloud computing practices and expertise. We are on a mission to build a robust cloud computing ecosystem by disseminating knowledge on technological intricacies within the cloud space. Our blogs, webinars, case studies, and white papers enable all the stakeholders in the cloud computing sphere.
To get started, go through our Consultancy page and Managed Services Package that is CloudThat ’s offerings.
1. Can we assign the same role to multiple users with the same steps above?
ANS: – Yes, we need to use the assigned role REST API to assign one more user, get the new principal ID of any user and replace it in the request body.
2. Can we create the roles based on the permissions to what resources we want to give?
ANS: – Yes, we must give those conditions in the actions key to creating a role sample request body.
- App Registration
- Azure REST API
- Cloud Computing
WRITTEN BY Sridhar Andavarapu
Sridhar works as a Research Associate at CloudThat. He is highly skilled in both frontend and backend with good practical knowledge of various skills like Python, Azure Services, AWS Services, and ReactJS. Sridhar is interested in sharing his knowledge with others for improving their skills too.
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.
Related Resources
Discover our most popular courses for self learning
Microsoft 365, Microsoft Dynamics 365
Streamlining Business Operations: Azure Integration with Dynamics CRM 365
By Anoop H A
May 16, 2024
Demystifying Gen AI: A Beginners Guide
Upcoming Webinar
Demystifying Generative BI: A Deep Dive with Amazon QuickSight
May 9, 2024
AWS, Cloud Computing
The Rise of Amazon Q: How to Stay Ahead
By Rajesh KVN
May 7, 2024
DevOps, DevSecOps
Proven Practices of Integrating Azure CI/CD pipeline with DevSecOps
By Tanvi Puri
Restricting Unauthorized Access and Achieving 77% Compliance with AWS
By Sohail Yaragatti
May 3, 2024
Continuous Monitoring for Illegal or Malicious Activity and Enhancing
Achieving 70% Completion within the Priority Timeline and Implementing
Azure, Microsoft Azure
Microsoft Intune: Empowering Modern Device Management and Security
By Aadish Jain
Strengthening Defenses Against Common Web Exploits and Malicious IPs
May 2, 2024
Get The Most Out Of Us
Our support doesn't end here. We have monthly newsletters, study guides, practice questions, and more to assist you in upgrading your cloud career. Subscribe to get them all!
©COPYRIGHT 2024 CLOUDTHAT TECHNOLOGIES PRIVATE LIMITED · ALL RIGHTS RESERVED · PRIVACY POLICY · TERMS OF USE · DISCLAIMER · CANCELLATION AND REFUND
Microsoft Azure provides a number of ways to interact with Azure resources
- Azure SDKs in many languages, including .NET, Python, Java, JavaScript/TypeScript, Go, C++, C, Android, iOS, PHP, and Ruby
- Azure CLI to execute commands
- Azure REST APIs
Learn how to get started with Azure APIs in Postman. If you are using Azure APIs for the first time, you can follow the steps in this guide to call the APIs using requests sent through the Postman client. You can use these requests to experiment with an API before you develop your application, or programmatically run a sequence of API calls to create and manage your infrastructure on Azure.
Prerequisites
- Basic familiarity with APIs
- Basic familiarity with CLI
What You'll Learn
- how to authenticate to Azure APIs using roles
- how to authenticate to Azure APIs using API keys
- how to add resource groups with Azure APIs
- how to troubleshoot unexpected API behavior
- how to automate API workflows for Azure in Postman
What You'll Need
- You must be an Owner or have Microsoft.Authorization/roleAssignments/write permissions to manage role assignments
- Or have a service principal with Contributor role to create and manage resources
- Download and install Postman Desktop App
- For Windows
What You'll Build
- A Postman Collection with authorized API requests
- Code samples to integrate into your own workflows and applications
- API workflows to automate the setup of your infrastructure
In this section, let's use the Azure CLI to generate credentials, and explore how to authenticate with the Azure REST APIs .
Get credentials using Azure CLI
- Select an active subscription : Select an active Azure subscription using the az account set command. Use the -n parameter to specify the subscription name, i.e: az account set -n "MSDN Platforms Subscription" . A list of your subscriptions can be found in the Azure portal.
- displayname
- Owner - Total control of a Resource Group
- Contributor - Has control on Actions on a Resource Group like modifying a Resource Group (i.e. Deleting a VM) but cannot assign permission to the RG.
- Reader - only has the ability to view the resource group.
- Get the subscription ID for your Azure Instance : From the terminal, use the Azure CLI command az account show --query id -o tsv or az account subscription list . The output should look like the following: az account subscription list The command requires the extension account. Do you want to install it now? The command will continue to run after the extension is installed. (Y/n): y Run 'az config set extension.use_dynamic_install=yes_without_prompt' to allow installing extensions without prompt. Command group 'account subscription' is experimental and under development. Reference and support levels: https://aka.ms/CLI_refstatus [ { "authorizationSource": "Legacy", "displayName": "MSDN Platforms Subscription", "id": "/subscriptions/[subscription ID]", "state": "Enabled", "subscriptionId": "[subscription ID]", "subscriptionPolicies": { "locationPlacementId": "Public_2014-XX-XX", "quotaId": "MSDN_2014-XX-XX", "spendingLimit": "On" } } ]
Input Azure credentials into Postman
Generate bearer token for authorization
- Review code : Select the Postman collection that you forked to your workspace. Find the Pre-request Script tab containing JavaScript that will execute before every request in the collection. The code will retrieve an OAuth 2.0 bearer token, and then save the value as a collection variable to be re-used throughout the collection. pm.test("Check for collectionVariables", function () { let vars = ['clientId', 'clientSecret', 'tenantId', 'subscriptionId']; vars.forEach(function (item, index, array) { console.log(item, index); pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.undefined; pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.empty; }); if (!pm.collectionVariables.get("bearerToken") || Date.now() > new Date(pm.collectionVariables.get("bearerTokenExpiresOn") * 1000)) { pm.sendRequest({ url: 'https://login.microsoftonline.com/' + pm.collectionVariables.get("tenantId") + '/oauth2/token', method: 'POST', header: 'Content-Type: application/x-www-form-urlencoded', body: { mode: 'urlencoded', urlencoded: [ { key: "grant_type", value: "client_credentials", disabled: false }, { key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false }, { key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false }, { key: "resource", value: pm.collectionVariables.get("resource") || "https://management.azure.com/", disabled: false } ] } }, function (err, res) { if (err) { console.log(err); } else { let resJson = res.json(); pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_on); pm.collectionVariables.set("bearerToken", resJson.access_token); } }); } });
Now that you have properly configured the authorization at the collection-level, you can re-use it throughout other requests within the collection, unless otherwise configured.
In the next sections, let's explore other Azure APIs.
In the previous section, you may have already made your first successful Azure REST API request. Let's review.
Check out other Azure REST APIs for the Resource Group .
For each Azure resource that you plan to work with, add the resource to your resource group.
Each of the following APIs will explore a specific Azure resource corresponding to the specific AI service as a prerequisite. However, if you will be using multiple AI services in the same project, you can create a Cognitive Services resource instead, which provides access to Vision, Language, Search, and Speech services using a single API.
Not all of the following services are available in every region. Please refer to Azure Products by Region to ensure that you pick a correct region when creating your resource.
Cognitive Search
Azure Cognitive Search is a cloud search service that gives developers infrastructure, APIs, and tools for building a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications.
Create resource and index
- Customize target index : Accept the system-generated values. Select Next: Create an indexer to continue.
- Create an indexer : Accept the system-generated values. Select Submit to create and simultaneously run the indexer.
Authorization
- Input Postman variables : In addition to adding your API key as a collection variable, update the searchServiceName and searchIndexName to begin exploring the Azure Cognitive Search API.
Other AI APIs
In Postman, explore other Azure AI services within the "AI" folder. Notice folder-level authorization methods. And expand the request documentation using the icon on the far right for more details and links to additional resources.
Debugging unexpected behavior
If your API request isn't behaving as expected, there can be many possible reasons. To find out what the problem is, you can use the Postman Console to troubleshoot your request.
Organize workflows in Postman
Once you explore an API, you understand the basic building blocks of popular services on Azure. Next, organize your work into your own collections and workspaces in Postman.
- Create your own collections of API calls for automating deployments and monitoring infrastructure.
- Create your own workspaces to organize work for an API or collaborate with team members.
Automate workflows in Postman
Once you group API requests into collections, there are multiple ways to programmatically run those collections.
- Add tests and scripts to dynamically pass information from one request to another
- Utilize inbuilt Postman integrations, such as deploying to Azure API Management
- Run collections on a scheduled frequency on Postman servers, as part of your CI/CD pipeline, or via webhooks
Build your own applications
What we've covered
For more hands-on tutorials, check out these resources.
- Check back for more Azure tutorials
- Contribute your own tutorials here
Other Azure integrations in Postman
- Azure DevOps to sync your Postman APIs to Git repositories
- Manage API deployments to Azure API Management in Postman
- Integrate Postman with Azure Pipelines
- Configure SSO with Microsoft Entra ID (formerly Azure Active Directory )
- Connect your API to an on-premises Git repository
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
Authentication for Azure REST APIs using Azure AD Service Principals
In this article, we will explore how to make a REST API call to Azure resources to manipulate (CRUD) them.
Azure REST APIs require authentication that confirms that we or the application as the user has the appropriate permissions to perform the given action - this is achieved by creating a Service Principal (SPN) in Azure Active Directory (AD) and acquiring a Bearer Token to authenticate
.css-1qh5hbx{box-sizing:border-box;margin:0;min-width:0;display:block;color:var(--theme-ui-colors-heading,#2d3748);font-weight:bold;-webkit-text-decoration:none;text-decoration:none;margin-bottom:1rem;font-size:1.5rem;position:relative;} Creating a Service Principal and generating ClientID/ ClientSecret(via Portal)
There are five inputs to be noted:
- Client ID (Application ID)
- Client Secret (Client Secret can be generated from the following steps)
- Tenant ID (Directory ID)
- Subscription ID (Obtained from the Subscriptions)
Add a Role Assignment with the Service Principal (via Portal)
The Service Principal created only defines the object and would need to be Role assigned to which resource that is allowed via the object to be accessed.
Creating SPN and assigning a Role, and generating a Client Secret (via Azure CLI)
The Azure CLI can be used to create the Service Principal, assign the role, and then create the required Client ID and with the Cloud Shell CLI or local Azure CLI (Pretty much avoiding going through Portal as above!) This section can be skipped if you have already created the SPN, assinged role and have the Client ID and Client Secret generated.
- Successful assignment of the Role can be checked by navigating to the Resource >> Access Control (IAM) >> Role Assignments and the SPN should be listed with the correct access role.
Acquiring an AD Access Token
The Access Token can be acquired by using any REST Client, in this example we will use PostMan and an example using PowerShell command
.css-v8d1oj{box-sizing:border-box;margin:0;min-width:0;display:block;color:var(--theme-ui-colors-heading,#2d3748);font-weight:bold;-webkit-text-decoration:none;text-decoration:none;margin-bottom:1rem;font-size:1.063rem;position:relative;} PostMan
- ContentType = x-www-form-urlencoded
- grant_type = client_credentials
- client_id = Generated from the steps before (appID in the Command output or Application Client ID from the portal)
- client_secret = Generated from the client password generation step (password noted in the Command output)
- resource = https://management.azure.com/ (depends on the resource being accessed, Refer API Documentation)
The AD Bearer Token can also be acquired by the Powershell commands (without using Postman)
I have broken it down into variables to demonstrate how the request is constructed.
Testing Access with Postman
Set the Header to “Authorization” and value as “Bearer <TokenValue > ” (note the space between the Bearer and Token
and the response returns 200 OK and Succeeded state for this example.
The requested “env” tag is successfully created in the Resource Group via Azure REST API! 😀
Refer the Azure REST API Documentation for other actions
Common Issues
- If you forget/miss to copy the Client Secret, you can always reset it from Azure CLI
Add —append flag if you want to create the new secret as addtional secret
- Resource access doesn’t have permission
Check if the created SPN is correctly role assigned (Role Assignment) to the resources accessed, or generate a new Bearer token if changes were recently made.
Hope that was helpful! :)
Aby Thannikal Joseph
Table of contents.
Legal Stuff
Social Media
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Role Assignments - Create
Create or update a role assignment by scope and name.
URI Parameters
Request body, permissions.
To call this API, you must be assigned a role that has the following permissions. For more information, see Azure built-in roles .
Microsoft.Authorization/roleAssignments/write
Azure Active Directory OAuth2 Flow
Type: oauth2 Flow: implicit Authorization URL: https://login.microsoftonline.com/common/oauth2/authorize
Create role assignment for resource
Sample request.
To use the Azure SDK library in your project, see this documentation . To provide feedback on this code sample, open a GitHub issue
Sample Response
Create role assignment for resource group, create role assignment for subscription, definitions, error additional info.
The resource management error additional info.
Error Detail
The error detail.
Error Response
Error response
Principal Type
The principal type of the assigned principal ID.
Role Assignment
Role Assignments
Role Assignment Create Parameters
Role assignment create parameters.
IMAGES
VIDEO
COMMENTS
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 ...
Click on Add role assignment. 5. Search for the custom role created in step 3 -> click Next. ... Developers can leverage the Azure REST API for creating and assigning roles to users or principal ID of an App Registration. This would also be the best way to implement this in the prospect of application. This REST API plays a crucial role in ...
Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question.Provide details and share your research! But avoid …. Asking for help, clarification, or responding to other answers.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.
Create a service principal: Azure REST API authentication is done via a Bearer token in the Authentication header. Let's use a service principal to get that token for us. A service principal is an Azure account that allows you to perform actions on Azure resources. ... You would also need to add a role assignment to grant scope permissions ...
"description": "Role based access control provides you a way to apply granular level policy administration down to individual resources or resource groups. These operations enable you to manage role assignments. A role assignment grants access to Azure Active Directory users."},
In this article, we will explore how to make a REST API call to Azure resources to manipulate (CRUD) them. Azure REST APIs require authentication that confirms that we or the application as the user has the appropriate permissions to perform the given action - this is achieved by creating a Service Principal (SPN) in Azure Active Directory (AD ...
In Azure, there are five ways to assign roles to developers or anyone: Portal. Azure CLI. Azure PowerShell. REST API. Azure Resource Manager (ARM) Templates. Here are the commands for Azure CLI ...
Learn more about Authorization service - Create or update a role assignment by scope and name. Skip to main content. This browser is no longer supported. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. ... API Version: 2022-04-01 ...
The following PowerShell script will enable Administrators and developers to create App roles in existing App registrations easily. Please note that under the hood the PowerShell script is also using MS Graph APIs and the permissions requirements remain identical to the one from method #1. Connect-AzureAD -TenantId <TenantId>.
Azure Cognitive Account - Kind Open AI. Open AI Services. Azure OpenAI Service provides REST API access to OpenAI's powerful language models including the GPT-3.5-Turbo model series, GPT-4, GPT-4 Turbo with Vision, GPT-4o & GPT-4 Turbo NEW and Embeddings model series. These models can be easily adapted to your specific task including but not ...
The roleAssignmentName is a GUID that uniquely identifies the role assignment. The API version is specified as api-version=2015-07-01. Any guidance on how to construct the DELETE request URL correctly would be greatly appreciated. I am trying to delete a role assignment at the root level in Azure using the REST API.
How do I get the role assignments like data curators, collection admins and the name of the users and service principals. You need to make below calls to get the name of the users and service principals.
Im trying to assign the role to my storage account, using the object IDs. One is the Entra ID group and the other one is the object ID of the access connector. It happens that only access connector getting assigned correctly. but not the entra id. Below is my code: storage_accounts = {. adls = {. "Storage Blob Data Contributor" = {.