如何使用 Powershell Function App 从 AAD 获取组?

How do I get groups from AAD using Powershell Function App?

我想使用带有函数应用程序的 Powershell 获取 AAD 中某些组的所有用户,但我不断收到权限错误,我不知道如何分配它们。

$groupsAD = [System.Collections.ArrayList]@()
      $groupsAD.Add('Group1')
      $groupsAD.Add('Group2')

foreach ($groupAD in $groupsAD) {
    $group = Get-AzADGroup -DisplayName $groupAD
    # further code

}

错误:

[Error] ERROR: Insufficient privileges to complete the operation.Exception :Type : System.ExceptionMessage : Insufficient privileges to complete the operation.HResult : -2146233088CategoryInfo : InvalidOperation: (:) [Get-AzADGroup], ExceptionFullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.GetAzureADGroupCommandInvocationInfo :MyCommand : Get-AzADGroupScriptLineNumber : 16OffsetInLine
: 14HistoryId : 1ScriptName : C:\home\site\wwwroot\HttpTrigger1\run.ps1Line : $group = Get-AzADGroup -DisplayName $groupADPositionMessage : At C:\home\site\wwwroot\HttpTrigger\run.ps1:16 char:14+ $group = Get-AzADGroup -DisplayName $groupAD

在本地创建此函数时,在我使用 Connect-AzAccount 进行身份验证后它可以正常工作。 还尝试创建一个身份并使用它对其进行身份验证,但据我所知,它适用于 Azure 资源而不是 AAD。

针对这个问题,这里提供两种解决方案供大家参考:

1.如果在Connect-AzAccount命令中使用username/password进行认证,需要确保用户账号有获取AD所需的权限团体。然后在您的函数中使用以下代码:

$User = "{username}"
$PWord = ConvertTo-SecureString -String "{password}" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
Connect-AzAccount -Credential $Credential

$group = Get-AzADGroup -DisplayName "{group name}"

2. 如果你不想在你的函数中使用username/password做认证。您可以使用服务主体来完成它。

首先你需要在你的 Azure AD 中 register 一个应用程序,我在我的 Azure AD 中注册了一个名为“huryGetToken6”的应用程序。

然后单击“证书和机密”选项卡,新建客户端机密。将客户端密码复制到您的记事本。

然后将权限添加到已注册的应用程序中,按照以下屏幕截图中的步骤进行。

请不要忘记在为已注册的应用程序添加权限后点击“为 xxx 授予管理员许可”。

之后,您可以在您的函数中使用以下代码获取广告组:

$username = "{client id/application id}"
$password = "{client secret}"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd
Connect-AzAccount -Credential $Credential -Tenant "{tenant id}" -ServicePrincipal

$group = Get-AzADGroup -DisplayName "huryGroup"

对于上述命令中的参数,您可以在您注册的应用程序的“概览”页面中找到客户端id/application id 和租户id。