- 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?
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
[2] Using a Service Principal to connect to a directory in PowerShell
来源:https://stackoverflow.com/questions/51759015/azure-active-directory-add-service-principal-to-directory-readers-role-with-pow