Azure Active Directory:使用 PowerShell 将服务主体添加到目录读取者角色


  • VSTS 中的自承载代理上运行时,Azure PowerShell 任务中的命令(Get-AzureRmADUser -Mail $user).Id返回 null
  • 问题是服务主体需要具有从活动目录读取的权限

如何向服务主体授予从 Azure 活动目录读取的正确权限?

先决条件

  • 检查是否具有从服务主体获取对象 ID 的适当权限
  • 检查你是否具有将服务主体添加到 Azure Active Directory 租户中的"目录读取者"角色的适当权限(->管理员(

步骤

  • 通过Install-Module AzureAD安装 Azure AD 模块 [1]

  • 连接到 Azure Active Directory

    • Connect-AzureAD
  • 获取"目录读取者"角色的 ID

    • $roleId = (Get-AzureADDirectoryRole | where-object {$_.DisplayName -eq "Directory Readers"}).Objectid
  • 获取服务主体对象 ID

    • $spObjectId = (Get-AzureADServicePrincipal -SearchString "spName").ObjectId
      • 当然,这仅在结果仅包含一个 ObjectId 时才有效
      • 这不是在 Azure Active Directory 中注册的应用程序的 ObjectId
  • 将服务主体添加到"目录读取者"角色

    • Add-AzureADDirectoryRoleMember -ObjectId $roleId -RefObjectId $spObjectId
  • 检查是否将 SP 分配给目录读取者角色

    • Get-AzureADDirectoryRoleMember -ObjectId $roleId | Where-Object {$_.ObjectId -eq $spObjectId}
  • 如果要在稍后阶段从角色中删除服务主体

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

参见 [2]

资源

[1] 安装 Azure AD 模块

[2] 使用服务主体连接到 PowerShell 中的目录

最新更新