Azure Active Directory: Add Service Principal to Directory Readers Role with PowerShell
Asked Answered
D

1

0
  • The command (Get-AzureRmADUser -Mail $user).Id in a Azure PowerShell Task returned null when running on a self-hosted agent in VSTS
  • The problem was that the Service Principal needs to have the permission to read from the Active Directory

How can I give the the Service Principal the correct permissions to read from the Azure Active Directory?

Daile answered 9/8, 2018 at 4:46 Comment(3)
this is not a question, you could better have this as a blog post!Wells
What is so bad about having this here? It is based on a question (why (Get-AzureRmADUser -Mail $user).Id returns null) and directly provides the answer. Don't know what your problem actually is.Daile
If you vote down please provide a reason whyDaile
D
2

Prerequisites

  • Check if you have the proper permissions to get the object id from a Service Principal
  • Check if you have the proper permissions to add the Service Principal to the "Directory Readers" role in the Azure Active Directory tenant (-> Admin)

Steps

  • Install the Azure AD Module via Install-Module AzureAD [1]

  • Connect to the Azure Active Directory

    • Connect-AzureAD
  • Get the Id of the "Directory Readers" role

    • $roleId = (Get-AzureADDirectoryRole | where-object {$_.DisplayName -eq "Directory Readers"}).Objectid
  • Get the Service Principal Object ID

    • $spObjectId = (Get-AzureADServicePrincipal -SearchString "spName").ObjectId
      • This of course only works if the result includes only one ObjectId
      • This is not the ObjectId of the application registered in the Azure Active Directory
  • Add service principal to the "Directory Readers" role

    • Add-AzureADDirectoryRoleMember -ObjectId $roleId -RefObjectId $spObjectId
  • Check if SP is assigned to the Directory Readers role

    • Get-AzureADDirectoryRoleMember -ObjectId $roleId | Where-Object {$_.ObjectId -eq $spObjectId}
  • If you want to remove the Service Principal from the role at a later stage

    • Remove-AzureADDirectoryRoleMember -ObjectId $roleId -MemberId $spObjectId

See also [2]

Resources

[1] Install Azure AD Module

[2] Using a Service Principal to connect to a directory in PowerShell

Daile answered 9/8, 2018 at 4:46 Comment(2)
do we have an azure cli version of those commandsOdrick
not CLI but the graph API is available. which can be used using az rest learn.microsoft.com/en-us/azure/active-directory/roles/…Aphasia

© 2022 - 2024 — McMap. All rights reserved.