This browser is no longer supported.

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

Steps to assign an Azure role

  • 4 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 the high-level steps to assign Azure roles using the Azure portal , Azure PowerShell , Azure CLI , or the REST API .

Step 1: Determine who needs access

You first need to determine who needs access. You can assign a role to a user, group, service principal, or managed identity. This is also called a security principal .

Security principal for a role assignment

  • User - An individual who has a profile in Microsoft Entra ID. You can also assign roles to users in other tenants. For information about users in other organizations, see Microsoft Entra B2B .
  • Group - A set of users created in Microsoft Entra ID. When you assign a role to a group, all users within that group have that role.
  • Service principal - A security identity used by applications or services to access specific Azure resources. You can think of it as a user identity (username and password or certificate) for an application.
  • Managed identity - An identity in Microsoft Entra ID that is automatically managed by Azure. You typically use managed identities when developing cloud applications to manage the credentials for authenticating to Azure services.

Step 2: Select the appropriate role

Permissions are grouped together into a role definition . It's typically just called a role . You can select from a list of several built-in roles. If the built-in roles don't meet the specific needs of your organization, you can create your own custom roles.

Role definition for a role assignment

Roles are organized into job function roles and privileged administrator roles.

Job function roles

Job function roles allow management of specific Azure resources. For example, the Virtual Machine Contributor role allows a user to create and manage virtual machines. To select the appropriate job function role, use these steps:

Begin with the comprehensive article, Azure built-in roles . The table at the top of the article is an index into the details later in the article.

In that article, navigate to the service category (such as compute, storage, and databases) for the resource to which you want to grant permissions. The easiest way to find what your looking for is typically to search the page for a relevant keyword, like "blob", "virtual machine", and so on.

Review the roles listed for the service category and identify the specific actions you need. Again, always start with the most restrictive role.

For example, if a security principal needs to read blobs in an Azure storage account, but doesn't need write access, then choose Storage Blob Data Reader rather than Storage Blob Data Contributor (and definitely not the administrator-level Storage Blob Data Owner role). You can always update the role assignments later as needed.

If you don't find a suitable role, you can create a custom role .

Privileged administrator roles

Privileged administrator roles are roles that grant privileged administrator access, such as the ability to manage Azure resources or assign roles to other users. The following roles are considered privileged and apply to all resource types.

For best practices when using privileged administrator role assignments, see Best practices for Azure RBAC . For more information, see Privileged administrator role definition .

Step 3: Identify the needed scope

Scope is the set of resources that the access applies to. In Azure, you can specify a scope at four levels: management group , subscription, resource group , and resource. Scopes are structured in a parent-child relationship. Each level of hierarchy makes the scope more specific. You can assign roles at any of these levels of scope. The level you select determines how widely the role is applied. Lower levels inherit role permissions from higher levels.

Scope for a role assignment

When you assign a role at a parent scope, those permissions are inherited to the child scopes. For example:

  • If you assign the Reader role to a user at the management group scope, that user can read everything in all subscriptions in the management group.
  • If you assign the Billing Reader role to a group at the subscription scope, the members of that group can read billing data for every resource group and resource in the subscription.
  • If you assign the Contributor role to an application at the resource group scope, it can manage resources of all types in that resource group, but not other resource groups in the subscription.

It's a best practice to grant security principals the least privilege they need to perform their job. Avoid assigning broader roles at broader scopes even if it initially seems more convenient. By limiting roles and scopes, you limit what resources are at risk if the security principal is ever compromised. For more information, see Understand scope .

Step 4: Check your prerequisites

To assign roles, you must be signed in with a user that is assigned a role that has role assignments write permission, such as Role Based Access Control Administrator at the scope you are trying to assign the role. Similarly, to remove a role assignment, you must have the role assignments delete permission.

  • Microsoft.Authorization/roleAssignments/write
  • Microsoft.Authorization/roleAssignments/delete

If your user account doesn't have permission to assign a role within your subscription, you see an error message that your account "does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write'." In this case, contact the administrators of your subscription as they can assign the permissions on your behalf.

If you are using a service principal to assign roles, you might get the error "Insufficient privileges to complete the operation." This error is likely because Azure is attempting to look up the assignee identity in Microsoft Entra ID and the service principal cannot read Microsoft Entra ID by default. In this case, you need to grant the service principal permissions to read data in the directory. Alternatively, if you are using Azure CLI, you can create the role assignment by using the assignee object ID to skip the Microsoft Entra lookup. For more information, see Troubleshoot Azure RBAC .

Step 5: Assign role

Once you know the security principal, role, and scope, you can assign the role. You can assign roles using the Azure portal, Azure PowerShell, Azure CLI, Azure SDKs, or REST APIs.

You can have up to 4000 role assignments in each subscription. This limit includes role assignments at the subscription, resource group, and resource scopes. You can have up to 500 role assignments in each management group. For more information, see Troubleshoot Azure RBAC limits .

Check out the following articles for detailed steps for how to assign roles.

  • Assign Azure roles using the Azure portal
  • Assign Azure roles using Azure PowerShell
  • Assign Azure roles using Azure CLI
  • Assign Azure roles using the REST API
  • Tutorial: Grant a user access to Azure resources using the Azure portal

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

Identity Man

The site will help you getting to know more about the microsoft cloud, azure ad service principals: all you need to know.

In this blog I will explain to you what a service principal is and how you can easily make use of them when running (automated) scripts.

Let’s first go over what a service principal exactly is. A service principal is the local representation, or application instance, of a global application object in a single tenant or directory. A service principal is an instance created from the application object and inherits certain properties from that application object. A service principal is created in each tenant where the application is used and references the globally unique app object.

In simple words this means a Service Principal can either be a reference to an application in another environment, or can refer to a (gateway-) application which is hosted in- and connected to your tenant. The service principal object defines what the application can actually do in your tenant, who can access the app, and what resources the app can access.

Each application you see in the Enterprise Applications overview in Azure AD can therefore be referred to as a service principal. If you use PowerShell to retrieve those the cmdlet is Get-AzureADServicePrincipal , this will display all Enterprise Applications within the Azure AD.

add role assignment to service principal

Now we do know that a lot of applications are already using Service Principals, but we can of course create one and consume it for our own needs. For example for tasks for which we are currently using service accounts This would then eliminate the use of service accounts, which is a big advantage as the service principal doesn’t exist of a username and password, and cannot be logged in with interactively from for example a portal page, it is therefore less likely to be impacted when it comes to brute force attacks! So by using service principals we can replace service accounts currently used and therefore improve the security posture of your environment!

More information about the difference between Service Principals and App Registrations can be found here .

Create a Service Principal

Now that we know what a Service Principal is, let’s create one. For that, go to the Azure Portal , open the Azure Active Directory blade and go to the Enterprise Applications section. In here make sure ‘All applications’ is selected and hit ‘+ New Application’ .

add role assignment to service principal

Now hit ‘+ Create your own application’ , as there is no app listed we can use for our own service principal.

add role assignment to service principal

On the right side of the screen make sure you give the application a friendly name, which you can easily refer to. This name is displayed as well in the logs so make sure it’s recognizable for others as well. Once the friendly name has been determined, please select ‘Intergrate any other application you don’t find in the gallery’ and hit ‘Create’ .

add role assignment to service principal

Once created, you will see that we have created an Enterprise Application within the Azure AD Portal and this can be referred to as a Service Principal, as explained earlier.

Important to know is that, in the background, an App Registration has been created as well for the service principal, whereby the application ID is matching and the Objectids are different . This as the App Registration is simply a different object in your Azure AD, however both objects belong to the same application in Azure AD as you can see.

add role assignment to service principal

Configure Service Principal Certificates & Secrets

Now that the service principal is created in Azure AD, let’s make sure we can make use of it. To do that, go to the App Registration settings in Azure AD , make sure ‘All Applications’ is selected and select the service principal we just created. From here go to the ‘Certificates & Secrets’ section, as you can see no certificates and secrets have been added yet.

add role assignment to service principal

When using Service Principals there are two ways you can authenticate as that service principal:

Using a Certificate – This allows you to ‘link’ a certificate to the Service Principal which you can use for authentication. This can be a self-signed certificate. When authenticating using that certificate you will (likely) provide the thumbprint of the certificate to authenticate. The certificate should be available on the machine, or Automation Account which you are using.

Using a client secret – You can compare a client secret to a long & complex password which is generated for you. Although you can connect as the Service Principal by filling, for example a PowerShell credential with the AppID and client secret, you cannot simply go to https://portal.azure.com and provide the values to interactively log in as the Service Principal. Which, from a security point of view, is a good thing.

Pro-tip: When using Azure Automation, always remember to save your client secret as an encrypted value in your Automation account to make sure it cannot simply be copy/pasted out.

Now, depending on the module or application for which you want to use a service principal, first determine which methods are supported. Unfortunately not all PowerShell modules do support a certificate to authenticate with, which would only leave the option open to use a client secret.

If you would ask my honest opinion, a client secret is less secure compared to a certificate but safer than using a regular service account. Reason for that is that a certificate is something you need to know (Thumbprint) and something you need to have (the actual certificate) to run. While a client secret simply exists of something you know but doesn’t have a part of something you have.

Now let’s add both of the methods to see how you can make use of them. Let’s first start with the Client Secrets. Please hit ‘+ New client secret’ , beneath the ‘Certificates & Secrets’ section of the App Registration belonging to the Service Principal .

add role assignment to service principal

Create a friendly description for which this client secret will be used and set the expiration time. Please note that after this time this secret can’t be used anymore. And like with passwords I wouldn’t recommend to use the ‘Never’ value as this means the client secret (password) will never expire. Once done hit ‘Add’ .

add role assignment to service principal

Now the client secret has been created, please save the client secret value immediately, this as it will only be shown once .

add role assignment to service principal

After a few minutes or when doing a refresh it will show the value below and will never show the full value anymore. You will see the first few characters to be able to recognize the value should you want to validate its validity later on.

add role assignment to service principal

This is all we need to do to prepare the connection with a client secret.

Now when looking at certificate it becomes a bit more complex. This as we first need to generate a certificate. This can be done by using the PowerShell command shown below:

New-SelfSignedCertificate -CertStoreLocation “cert:\CurrentUser\My” -Subject “CN= Automation Service Principal ” -KeySpec KeyExchange -NotBefore ((Get-Date).AddDays(-1)) -NotAfter ((Get-Date). AddYears(5) )

Recommendation: Please change the common name (subject) to match the name of the service principal and configure the NotAfter time in the above PowerShell to match the validity your require.

add role assignment to service principal

Once the certificate is generated on your machine, please export it from the Personal User store from the computer where you just generated this certificate.

add role assignment to service principal

During the export make sure that the format is set to ‘ Base-64 encoded X.509 (.CER) ’ and without the private key.

add role assignment to service principal

Now when we go back to the App Registration of the service principal we have created and again go to ‘Certificates & Secrets’ we can hit ‘Upload Certificate’ .

add role assignment to service principal

In here select the certificate file we just created and exported and hit ‘Add’ .

add role assignment to service principal

Once the certificate is selected we can see the Thumbprint of the certificate in the Azure Portal as well.

add role assignment to service principal

Certificate based authentication on this service principal has now been enabled. From this point forward we can use this service principal and are able to connect based on a certificate and client secret connection.

Keep in mind the actual certificate is required to be present on the device/account connecting with it.

Configure Service Principal Permissions

Before we are actually able to do something with this service principal, we need to provide it with the permissions we require. In this case you need to find out yourself what kind of permissions you need and, important as well, know to which API you are connecting to.

In this example we are going to connect to the Microsoft Graph API. If you are using older API’s I would strongly recommend you to move to the Microsoft Graph API where possible. This, as older API’s like the Azure Active Directory API won’t get the latest and greatest functionality of all that Azure Active Directory has to offer.

Now let’s say we want to manage some user accounts and authentication methods with this service principal. Let’s add the permissions for that on the Service Principal we created. Therefore go to the App Registrations in Azure Active Directory, select the application which the service principal is connected to and select ‘API Permissions’ . In here hit ‘+ Add a permission’ .

add role assignment to service principal

The Request API permissions screen on the right will open, in here we can select the ‘Microsoft Graph’ API.

add role assignment to service principal

Once selected we can configure either Delegated or Application permissions , the difference between these two is quite simple. Delegated permissions are used when a user is connecting via this service principal. Meaning the service principal determines the permissions the process will get after a sign-in. Application permissions are used when the application itself is connecting, i.e. via the certificate or client secret which we have just created.

As a guideline: Using application permissions will allow the application to process actions completely independent, whereas delegated permissions require a user logon and will therefore provide the user the access based on the access configured on the Service Principal.

In this example we are going to use application permissions, therefore select ‘Application permissions’ .

add role assignment to service principal

Once selected we can see all the permissions we are able to select, as you can see there are a lot, but in our example we will only use ‘UserAuthenticationMethod.ReadWrite.All’ and ‘User.ReadWrite.All’ . Once done hit ‘Add Permissions’ .

add role assignment to service principal

Once added we must grant an admin consent, this can be noted from the column ‘Admin consent required’ where both values are set to ‘Yes’ . Therefore hit ‘Grant admin consent for …’ .

add role assignment to service principal

Please hit ‘Yes’ to confirm the admin consent approval.

add role assignment to service principal

As you can see the status will be checked with a ‘green checkbox’ stating that the admin consent is granted.

add role assignment to service principal

We are now ready to use the service principal in PowerShell scripts based on the above permissions. Again as in this example application permissions are used we can only use it based on the certificate or client secret configured beneath the service principal.

Using the Service Principal we created

Let’s first gather the required crucial information from the service principal itself. Which is the Application ID and Tenant ID . Both values are required to connect with PowerShell to the service Principal. Note the difference between the Application ID and the Object ID. These are two fundamentally different things, always check which ID you need when it is being requested. In (almost) all cases this will be the Application ID.

add role assignment to service principal

Now let’s connect using the certificate. First, make sure that the user account which is running the PowerShell session has the certificate stored in the personal user certificate store. If that’s not the case the logon will fail.

Once you’ve made sure that the certificate is in the personal user store, lets connect to the Microsoft Graph with the following PowerShell cmdlets:

Import-module Microsoft.Graph Connect-Graph -ClientId {applicationID} -TenantId {TenantID} -CertificateThumbprint {CertificateThumbprint}

Connect-Graph -ClientId d27624ba-040c-426f-bdd8-d57761c710c6 -TenantId ad7aaf9d-e478-4d3f-99aa-ce450535d9cc -CertificateThumbprint AB791BD89E1714732D22663C0103B9933CB7076E

add role assignment to service principal

Not sure about the certificate thumbprint? Use the command below to list all the available certificates on your machine:

Get-ChildItem -path cert:\LocalMachine\My

As you can see I’m successfully connected! And, to confirm the security measures in terms of API permissions, I’m not able to retrieve any groups from the Azure Active Directory.

add role assignment to service principal

Which is correct as I didn’t provide the permissions.

What we are able to do, however, is retrieve the users and check their authentication methods, i.e. the Windows Hello for Business authentication methods as you can see below via the command:

Get-MgUserAuthenticationWindowsHello -UserID [email protected]

add role assignment to service principal

As I provided access to read and write authentication methods, I’m able to delete these as well as you can see with the command:

Remove-MgUserAuthenticationWindowHello -UserId [email protected] -WindowsHelloForBusinessAuthenticationMethodId o8ylNeQ0a071RsrlyWdOn3zaDzOm4LyPNQ-DZgMMEcs1

add role assignment to service principal

As you can see I did some cleaning up on my test account! Once you or the script has finished, you can easily run the following command to disconnect from the Microsoft Graph API.

Disconnect-Graph

Important to note is that this sign-in is of course logged within the Azure AD under the sign-in logs beneath the ‘Service Principal Sign-ins’ .

add role assignment to service principal

Now let’s try something different, let’s say you want to connect to a regular Azure resource, i.e. a log analytics workspace as well with the same service principal, and want to use a client secret (which I wouldn’t recommend though if it supports certificate auth).

For that we first need to provide the service principal the right access permissions. This can be done on the Azure Resource, beneath the ‘Access control (IAM)’ settings by hitting ‘+ Add’ and selecting ‘Add role assignment’ .

add role assignment to service principal

As in this case the service principal only needs to gather data we just give it ‘Read’ access and we select the service principal ‘Automation Service Principal’ and once done we hit ‘Save’ .

add role assignment to service principal

We are now able to connect with PowerShell and the service principal to this log analytics workspace. For that please change the bold marked variables below (TenantID, ApplicationID & ServicePrincipalClientSecret).

$TenantId = “ ad7aaf9d-e478-4d3f-99aa-ce450535d9cc “ $ApplicationId = “ d27624ba-040c-426f-bdd8-d57761c710c6 “ $ServicePrincipalClientSecret = ConvertTo-SecureString -String “ Cw2DiqRvF67O_iz8p5h~Q3~hQ6hQb4K~Th ” -AsPlainText -Force $AzureADCred = New-Object System.Management.Automation.PSCredential ($ApplicationId, $ServicePrincipalClientSecret )

As you can tell we are simply filling a “regular” credential-object to connect with, in which the username is the Application ID, and the password is the Client Secret.

Once done execute the below PowerShell code to connect to the Azure environment with the service principal.

Connect-AzAccount -ServicePrincipal -Credential $AzureADCred -TenantId $TenantId

add role assignment to service principal

Once we have a look at the sign-in logs for the service principal, we again see that the service principal has connected successfully .

add role assignment to service principal

Now let’s say we want to retrieve some sign-in log data which is available within this log analytics workspace via this service principal. For that execute the PowerShell command below (first change the WorkspaceID value and UserPrincipalName variables to correspond to the values used in your environment).

#Define variables [string]$WorkspaceID = ’69b37e8d-870c-457a-8c98-f9e993e42318′ $UserPrincipalName = ‘[email protected]

#Create the query for log analytics workspace for last sign in for user which goes back 180 days $QuerySignInCount = ‘SigninLogs | where TimeGenerated > ago(180d) | where UserPrincipalName == “‘ + $UserPrincipalName + ‘” | summarize signInCount = count() by UserPrincipalName | sort by signInCount desc’

#Execute the query and summarize the count $ResultsSignInCount = Invoke-AzOperationalInsightsQuery -WorkspaceId $WorkspaceID -Query $QuerySignInCount $AADSigninCount = $ResultsSignInCount.Results.signInCount

#Write-ouput Write-output “User $UserPrincipalName has $AADSigninCount sign-ins in Azure AD in the last 180 days!”

add role assignment to service principal

As you can see Johny Bravo has two sign-ins in the past 180 days. Whereby this data is retrieved via the service principal from the Log analytics workspace in Azure! Once you or the script has finished you can easily run the following command to disconnect the PowerShell session.

Disconnect-AzAccount

Now you know how you can create a service principal and use it for your scripts which for example run from Azure Automation. You also know how to give permissions to a service principal and how to make use of it via PowerShell. An important take away, as also mentioned before, is the advice to always prefer a certificate above a client secret as that’s more secure. I hope you’ve enjoyed reading this blog and stay tuned for more coming soon!

Share this:

8 thoughts on “ azure ad service principals: all you need to know ”.

' src=

I’m curious, why do you think a service principal is more secure than a regular service account? i see a lot of people parroting this line, but I have never seen any argument in favour of it…

' src=

The biggest difference between a service account and a service principal is that it can’t be used for regular web based sign-ins. A service account exists of a username and a password. While in the best scenario a service principal exist of an AppID, TenantID and Cert Thumbprint. Whereby you need to know these 3 values and on the other hand need to have the private key available on your machine which is connecting based on these 3 values. Even when I do know the 3 values (AppID, TenantID and Cert Thumbprint) and don’t have the actual certificate installed with it’s private key I won’t be able to connect.

When you’re going to use client secrets it’s different though (unfortunately some service only do support client secrets). It’s still better than a regular service account (can’t be used for web-based sign ins) but only exists of things you need to know, hence the reason to use cert based auth where possible.

Lastly when using a SA account, i.e. to configure some permissions I can’t limit it down to very specific permissions via MS Graph. Via the app registration I can specifically determine the permissions the service principal needs, instead of over commiting permissions to a service account.

Hope those are enough reasons for you to start exploring and using service principals in the future and replace your service accounts :-)!

' src=

Thanks for the time you spent sharing your knowledge. Really well written .

Thanks and you’re very welcome :-)!

' src=

why do we need full access to service principal

Not sure what you mean with ‘full access’? The rights on the service principal can be configured based on the API permission you can configure your self, which is Read or ReadWrite, and that specific to a part of the information (or all). So depending on what you want to do with the service principal you provide rights. Not sure if this answers your question, otherwise a bit more explanation is required.

' src=

I really appreciate the time that you took to explain this topic. This is one of the best articles that I could find that explains this so well and well written. Thanks a lot for sharing.

' src=

Nice blog thanks for possting

Leave a comment Cancel reply

' src=

  • 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

Assigning Service Principals to Groups and Roles with the Azure CLI

The more I use Azure the more often I find myself needing to assign various managed identities / service principals to various groups and roles, and while that can be done in the Portal, it's cumbersome and I'd prefer to automate it.

So in this post I'll sharing a few Azure CLI commands that should prove useful whenever you're configuring Service Principals.

Getting a service principal's object id

Suppose you know the name of the service principal, but not the "object id", which is required for assigning it to groups and roles. You can use a filter with the az ad sp list command to find that service principal and then a query to pick out just the object id.

Note that you should avoid trying to use the query parameter to find the matching name, as that will likely not find it as it only applies to the first page of results .

Note that the object id is different from the app id. If you do need the app id for any reason you just need to change the query parameter:

Adding to a group

Suppose we want to add the service principal to a group. We need the group id to do that, and if we need to look it up, we can do so with the az ad group list command and using a filter .

Then the az ad group member add command allows us to add the object id of our service principal to the group.

Creating a role assignment

If we want to create a role assignment, then as well as knowing the user we're assigning the role to and the name of the role, we also need to provide a " scope " for that to apply to. This is typically a long / delimited path to an Azure resource. So for a KeyVault it might look like this:

You can of course construct this string yourself, but actually this is quite often just the "ID" of the resource as returned by the Azure CLI. So we could get the above value with the following command:

And now that we have the scope, we can simply use the az role assignment create to assign the role to our service principal, and we can pass the role name directly (in this example it's "Key Vault Administrator"):

Hope this proves useful to you.

AAD Support Notes

Random thoughts from an aad support engineer, granting azure ad service principal a azure ad directory role.

Occasionally customers utilize Azure AD service principals for automation of Azure AD management tasks. In this scenario, you must grant the service principal the necessary Azure AD directory role permissions to complete the task. This can be performed using AzureADPreview PowerShell module

NOTE: You can also now perform this directly from Azure AD Portal -> Roles and Administrators blade -> Role -> Add Assignments -> Select members -> Filter by service principal display name

Leave a Reply Cancel reply

You must be logged in to post a comment.

All about Microsoft 365

More on service principal permissions in Exchange Online

Few days back I briefly covered the advancements in Exchange Online’s support for service principal objects. In the context of said article, we only talked about Full access permissions, but since service principals are now supported objects in Exchange Online, the question remains which other functionalities support them. So let’s take a deeper look.

First, let’s briefly talk again about creating and managing service principal objects in Exchange Online. Since no process exists to synchronize Azure AD service principal objects to ExODS, you’ll need to create a matching representation of the SP object yourself. In order to do that, you can use the New-ServicePrincipal cmdlet, which by default is available to users assigned the Role Management role. You will need to specify the client ID (application ID) value, via the – AppId parameter, as well as the object ID, via the – ServiceId parameter. Here’s an example:

If you do not know the values for said parameters, you can obtain them from either the Azure AD blade > App registrations > Overview page, or via PowerShell ( Get-MsolServicePrincipal , Get-AzureADServicePrincipal or Get-MgServicePrincipal cmdlet, depending on which module you prefer). Do note that the New-ServicePrincipal does NOT validate the values, so make sure you double- and triple-check them.

To list the current set of service principal objects recognized by ExODS, use the Get-ServicePrincipal cmdlet. Interestingly enough, the RecipientType value for such objects is User , whereas the RecipientTypeDetails is ServicePrinciple (note the spelling!). You cannot however use the Get-User cmdlet to list them, and Get-Recipient with the corresponding filter doesn’t work either. The Set-ServicePrincipal cmdlet can be used to update an existing object, although the only property you can change is the DisplayName . Lastly, to delete an existing service principal object, use the Remove-ServicePrincipal cmdlet.

Now that we covered the basics of managing service principals in Exchange Online, let’s turn into delegating permissions. We already covered the Full access permission in the previous article, but as a refresher you can grant permission via the Add-MailboxPermission cmdlet, by specifying the service principal identifier (display name, appId and serviceId will all work) as value for the -User parameter:

You can list, update and remove Full access permissions via the standard cmdlets. The EAC UI will display existing permission entries for service principal objects, but not allow you do add new ones. Interestingly, the new EAC will show you the GUID of the service principal, whereas the classic one returns its Display name. Another interesting thing is that the REST-based cmdlets cannot seem to resolve service principal objects by their DisplayName values, so you have to specify GUIDs instead:

Checking service principal permissions via PowerShell

As with Full access permissions, the EAC UI will show you any existing entries, but does not allow you to grant the permissions, so you have to stick to PowerShell. Even PowerShell however does not support granting Send on Behalf of or folder-level permissions, at least currently. So it seems currently only Full Access/Send As permissions are supported. Granting permissions aside, just how one would leverage them is not clear either, the only example of using Full access permissions granted to service principal can be found in this EHLO blog and the script linked therein.

We still have one last set of permissions to cover though, namely granting administrative permissions to the service principal object by assigning RBAC roles, or adding it as a member of a Role Group. Both operations seem to be possible (via PowerShell), but there are some very important caveats to consider. In a nutshell, only specific roles are supported, as we will see below.

For now, let’s see what happens if we try to create a direct role assignment to a service principal object. We can select a random role, such as say “Federated Sharing”, and try to assign it to the SP via the New-ManagementRoleAssignment cmdlet. Doing so will result in the following error message:

So while the process fails, the error message itself gives us a clue. Apparently, few months back Microsoft introduced a new type of role, a Service principal role, and a corresponding parameter was added to all existing roles, namely IsServicePrincipalRole . This is illustrated by the following cmdlet

I’ve truncated the output above, but since all the SP roles (the ones with IsServicePrincipalRole = True) have names starting with “Application”, we now have the full list of such roles. Interestingly, most of the roles seem to correspond to specific Graph permissions, such as Mail.Read. Another interesting observation is that a new Type property has been introduced for management role entries, with the corresponding parameter for the Get-ManagementRoleEntry cmdlet. In other words, you can also list all “ApplicationPermission” management role entries via the Get-ManagementRoleEntry cmdlet, as follows:

But I digress. Back to assigning admin permissions to service principal objects now. As we established above, direct role assignment is only possible for specific roles, such as the “Application Mail.ReadBasic” one:

For all non-SP roles, direct assignment will result in an error, as we already saw above. Turns out however that you can assign service principal objects as a member of a role group that contains non-SP roles. While the end result is disappointing, it’s still interesting to know that this is possible. Here’s how to assign a role group to a service principal object (as usual we have to use PowerShell):

where “test” is the identity of an already existing custom Role Group in my tenant. Usually, one can use the – GetEffectiveUsers switch of the Get-ManagementRoleAssignment cmdlet to “expand” role group based assignments and get a list of the corresponding user objects. This however does not seem to work with service principal objects, so you have to employ workarounds. Here are some examples:

Unfortunately, while the above examples show that it is indeed possible to add service principal objects as members of Role Groups, the permissions corresponding to any of the roles contained within said assignments are not available for use with the service principal login. One would hope that this method would finally allow us to use Role Groups for CBA scenarios for ExO PowerShell. However, this will result in an error as shown below:

The role assigned to application xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx isn’t supported in this scenario. Please check online documentation for assigning correct Directory Roles to Azure AD Application for EXO App-Only Authentication.

So in summary, Exchange Online now supports service principal objects. Those are objects of RecipientType User , with RecipientTypeDetails value set to ServicePrinciple . A new set of cmdlets has been introduced to manage them, namely *-ServicePrincipal . Service principal objects can be used to delegate Full Access and Send As permissions in app-only authentication scenarios, such as OAuth authentication via POP/IMAP. Folder level, delegate and send on behalf of permissions are not supported.

When it comes to admin permissions, service principal objects can of course be granted Azure AD admin roles. Within ExODS however, only a subset of the management roles are available for direct assignment – those designated with IsServicePrincipalRole value of True . And while you can add service principal objects as members of a group, including Role Groups, do not expect the corresponding cmdlets and functions to become available to the service principal. Well, perhaps any of the “Application *” ones would work 🙂

Before closing, it’s worth mentioning that you can use yet another “hack” to look at the full properties of the service principal object. Whereas the Get-ServicePrincipal cmdlet exposes only a handful of properties via the Deserialized.Microsoft.Exchange.Data.Directory.Management.ServicePrincipal object, you can get a lot more by fetching the Deserialized.Microsoft.Exchange.Data.Directory.Management.ReducedRecipient object as follows.

Few things to note here. The ExternalDirectoryObjectId value will match the clientID/appID of the parent application. No email addresses will be present and no Alias either, so while HiddenFromAddressListsEnabled is set to False, don’t expect to see service principal objects in the GAL. Interestingly, IsValidSecurityPrincipal is set to False, which is strange for an object that can be used for delegating permissions. But hey, it’s still in the early days I suppose.

I’ll circle back to this article at a later point to update it with new information as it becomes available. In any case, some more details on granting permissions to service principal objects and the corresponding use cases can be found in the official documentation .

13 thoughts on “ More on service principal permissions in Exchange Online ”

  • Pingback: ExO RBAC improvements #1: Limiting application access | Blog

' src=

Adding Service Pricipals to (custom) RBAC roles should work, as documented in the Exchange Blog post. https://techcommunity.microsoft.com/t5/exchange-team-blog/notes-from-the-field-using-app-only-authentication-with/ba-p/3690083

However, when following the steps, I also receive the error you got: The role assigned to application xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx isn’t supported in this scenario. Please check online documentation for assigning correct Directory Roles to Azure AD Application for EXO App-Only Authentication.

Did you manage to resolve that?

' src=

Seems to work fine here now, I can connect with just a Role Group assigned to the SP object, and the set of cmdlets I’m able to run is quite restricted. I’ll do a proper writeup in the coming days.

' src=

Which EXO module version are you using for this?

The New-ServicePrincipal cmdlet doesn’t appear to exist in version 3.0.1-Preview1 or 3.0.0.

Check your permissions 🙂

' src=

Your article helped me a lot, but some questions confused me. When I try to assign roles(actually the role is Application EWS.AccessAsApp) to the application(I use New-ManagementRoleAssignment mentioned in the article), I use this application through EWS to get mail. However, the returned result is 403 server forbidden. It seems that the application does not have permission. What can I do to use these permissions?

You don’t have to use these cmdlets for anything EWS related. Instead, make sure your Azure AD app registration has the necessary permissions, be it delegate or application ones, and that consent is granted. Here’s an article with more details: https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth

Thanks for your reply! I have tried the method you mentioned before. What really confuses me is what use are these roles(like Application Mail.ReadBasic) that can only be assigned to applications in Exchange? Or is it still unavailable?

Those roles are specific to Graph API operations.

After I use New-ManagementRoleAssignment to assign roles(Application Mail.ReadBasic) for the Azure AD application, the application still cannot use the graph api. Do you mean that these roles are internal and used in the graph api to access exchange, but cannot be used by ordinary users?

You cannot do this purely on Exchange side, the AAD application still needs to have the corresponding permission added and consented to.

' src=

Amazing article! thank you so much for taking the time to write this up, I’m sure it helps a lot of people.

While reading this I had an idea and I’m wondering if you tried it. One of the application permissions in Exchange Online is the “ApplicationImpersonation” one. Do you think this can be used to grant a user the necessary permissions and then grant the SP impersonation rights to that user? while looking at this I could only find documentation for impersonation in c# ( https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-add-appointments-by-using-exchange-impersonation ). But doing this in Powershell might be amazing.

What do you think?

Sure, EWS impersonation can be restricted to specific mailboxes only. Depending on the type of permissions you are using, you can either:

1) Application permissions model: Configure an Application access policy: https://practical365.com/new-application-access-policies-extend-support-for-more-scenarios/ 2) Delegate permissions model: Assign the user under whose identity your app is running to the ApplicationImpersonation role, with a custom management scope restricted to just the mailboxes you want him to be able to access

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 .

IMAGES

  1. What is Service Principal?

    add role assignment to service principal

  2. How to create Service Principal in Azure

    add role assignment to service principal

  3. Create a Microsoft Entra app and service principal in the portal

    add role assignment to service principal

  4. How to create Service Principal in Azure

    add role assignment to service principal

  5. How to Create a Service Principal for Azure Virtual WAN

    add role assignment to service principal

  6. Connect to an Azure Data Lake Storage account by using an Azure service

    add role assignment to service principal

VIDEO

  1. Assignment Topic: Customer Service

  2. Assignment Front page design 📝..(Part-12)WOW 😱 school project ideas 💡 #shorts #youtubeshorts #viral

  3. Vicarage and Deaconess Internship Assignment Service

  4. #IFMS 3.0 Employee Joining and Reliving Status kaise check karein

  5. NMIMS -June 2023 Assignment-Service Operation Management : SEM3

  6. Correct role is not mapped in UMP application #problemsolved #100% #add role #pmjay_card_delivery

COMMENTS

  1. Steps to assign an Azure role

    Step 2: Select the appropriate role. Step 3: Identify the needed scope. Step 4: Check your prerequisites. Show 2 more. 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 ...

  2. How To Use Service principal To Assign A Role To Another Service Principal

    The service principal also needs to be a Directory Reader, unless you specify the role assignment by object-id. Azure Active Directory: Add Service Principal to Directory Readers Role with PowerShell. It can be assigned to the service principal, and when executing az commands as that service principal, it succeeds in creating role assignments.

  3. Azure AD Service Principals: All you need to know!

    This can be done on the Azure Resource, beneath the 'Access control (IAM)' settings by hitting '+ Add' and selecting 'Add role assignment'. As in this case the service principal only needs to gather data we just give it 'Read' access and we select the service principal 'Automation Service Principal' and once done we hit ...

  4. Set Up Azure Service Principal: Unattended Access Guide

    Creating an Azure Service Principal with Automatically Assigned Secret Key. The heart of creating a new service principal in Azure is the New-AzAdServicePrincipal cmdlet. In this example, a new service principal will be created with these values: DisplayName: AzVM_Reader. Scope: AzVM1 (Virtual Machine) Role: Reader.

  5. Assigning Service Principals to Groups and Roles with the Azure CLI

    Adding to a group. Suppose we want to add the service principal to a group. We need the group id to do that, and if we need to look it up, we can do so with the az ad group list command and using a filter. --query "[].id" -o tsv. Then the az ad group member add command allows us to add the object id of our service principal to the group.

  6. Granting Azure AD Service Principal a Azure AD Directory Role

    In this scenario, you must grant the service principal the necessary Azure AD directory role permissions to complete the task. This can be performed using AzureADPreview PowerShell module. NOTE: You can also now perform this directly from Azure AD Portal -> Roles and Administrators blade -> Role -> Add Assignments -> Select members -> Filter by ...

  7. More on service principal permissions in Exchange Online

    Here's how to assign a role group to a service principal object (as usual we have to use PowerShell): 1. Add-RoleGroupMember -Identity test -Member 2a63aee1-db17-489d-a8ab-d40971066292. where "test" is the identity of an already existing custom Role Group in my tenant.

  8. Using Service Principals for Bicep deployments

    3. Assign a role to a Service Principal. To assign a role to a Service Principal, your own user account needs the User Access Administrator role assignment. To create the role assignment, you can ...

  9. Perform Role Assignments on Azure Resources from Azure Pipelines

    The Solution Option 1: Give the Service Principal access to the AD Graph API. In order to perform role assignment without modifying the role assignment command the AzDO service principal needs ...

  10. azurerm_role_assignment

    description - (Optional) The description for this Role Assignment. Changing this forces a new resource to be created. skip_service_principal_aad_check - (Optional) If the principal_id is a newly provisioned Service Principal set this value to true to skip the Azure Active Directory check which may fail due to

  11. Assign an app-role to a managed-identity service principal

    So I created an app role in the API's app registration. The normal guidance on how to assign such a role to an application can be found here (EDIT: WRONG LINK SEE ANSWER). However this does only apply to the service principal manually created (read: not a MSI) because this requires the service principal can be found in the portal UI.

  12. How can I grant roleAssignement/write permission to azure devops

    Grant below role to the devops service principle. Name:Privileged role administrator Description:Users with this role can manage role assignments in Azure Active Directory, as well as within Azure AD Privileged Identity Management. In addition, this role allows management of all aspects of Privileged Identity Management.