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?

quervernetzt
  • 10,311
  • 6
  • 32
  • 51

1 Answers1

1

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

quervernetzt
  • 10,311
  • 6
  • 32
  • 51
  • 1
    do we have an azure cli version of those commands – Tiju John Mar 22 '21 at 19:09
  • not CLI but the graph API is available. which can be used using `az rest` https://learn.microsoft.com/en-us/azure/active-directory/roles/custom-assign-graph#example-1-create-a-role-assignment-between-a-user-and-a-role-definition – Sagar Kulkarni Oct 29 '21 at 11:09