如何使用 Azure PowerShell SDK 向 Azure Active Directory (AAD) 应用程序添加所需的权限?

How do I add required permissions to an Azure Active Directory (AAD) application using the Azure PowerShell SDK?

在我的场景中,我试图自动创建我的一个 AAD 应用程序,以便它使用为此处的守护进程:

https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-daemon/

我已经能够通过 PowerShell 自动创建 AAD 应用程序和所需的访问密钥。

以下是我如何创建添加了密钥的应用程序:

# Generate all the keys (secrets) for the AAD application.
$passwordCredentials = @()

foreach ($key in $activeDirectoryApplication.Keys.Key)
{
    $keyKeyVaultName = $key.KeyVaultName
    $keyName = $key.KeyVaultKeyName
    $expiration = $key.Expiration

    LogInfo "Generating key with key name '$keyName' into key vault '$keyKeyVaultName' with key expiry of '$expiration'."
    $passwordCredential = GenerateActiveDirectoryApplicationKeyPasswordCredential $key
    $passwordCredentials += $passwordCredential

    PublishActiveDirectoryApplicationKeyToKeyVault $key $passwordCredential
}

$existingApplication = New-AzureRmADApplication -DisplayName $applicationName -HomePage $applicationHomePage -IdentifierUris @($applicationIdentifier) -PasswordCredentials $passwordCredentials

我想不通的是如何自动执行上述 link 中的第 8 步,其中授予访问 WebAPI 应用程序的权限:

  1. Configure Permissions for your application - in the Settings menu, choose the 'Required permissions' section, click on Add, then Select an API, and type 'TodoListService' in the textbox. Then, click on Select Permissions and select 'Access TodoListService'.

有谁知道这是否可以通过 Azure PowerShell SDK 实现,或者我是否需要通过其他方式(可能是 AAD Graph API)来实现?

谢谢!

要分配权限,您需要使用 New-AzureRmRoleAssignment。这将允许您在特定范围内为对象 (user\group\application) 分配权限。如果您需要内置角色,那您就可以开始了。如果您需要创建角色,请使用 New-AzureRmRoleDefinition.

$role = Get-AzureRmRoleDefinition "Virtual Machine Contributor"
$role.Id = $null
$role.Name = "Classic storage reader"
$role.Actions.Clear()
$role.Actions.Add("Microsoft.ClassicStorage/storageAccounts/read")
$role.AssignableScopes.Clear()
$role.AssignableScopes.Add("/subscriptions/xxxx")
New-AzureRmRoleDefinition -Role $role

阅读:
https://docs.microsoft.com/en-us/azure/active-directory/role-based-access-control-manage-access-powershell
https://docs.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermroleassignment?view=azurermps-4.1.0
https://docs.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermroledefinition?view=azurermps-4.1.0