我已经手动创建了Azure Active Directory应用程序。我想添加用户并通过PowerShell脚本分配用户角色。
我能够使用PowerShell脚本添加用户,但是无法在Azure活动目录应用程序的清单下添加应用程序角色。
是否可以通过PowerShell脚本添加应用程序角色?
答案 0 :(得分:5)
您可以在使用New-AzureADApplication创建新应用程序时,也可以在使用Set-AzureADApplication创建现有应用程序时执行此操作。我没有看到专门用于添加/删除角色的命令,这就是上面两个选项的原因。
下面是一个示例PowerShell脚本,用于向现有注册的应用程序添加新的应用程序角色:
Connect-AzureAD -TenantId <Tenant GUID>
# Create an application role of given name and description
Function CreateAppRole([string] $Name, [string] $Description)
{
$appRole = New-Object Microsoft.Open.AzureAD.Model.AppRole
$appRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]
$appRole.AllowedMemberTypes.Add("User");
$appRole.DisplayName = $Name
$appRole.Id = New-Guid
$appRole.IsEnabled = $true
$appRole.Description = $Description
$appRole.Value = $Name;
return $appRole
}
# ObjectId for application from App Registrations in your AzureAD
$appObjectId = "<Your Application Object Id>"
$app = Get-AzureADApplication -ObjectId $appObjectId
$appRoles = $app.AppRoles
Write-Host "App Roles before addition of new role.."
Write-Host $appRoles
$newRole = CreateAppRole -Name "MyNewApplicationRole" -Description "This is my new Application Role"
$appRoles.Add($newRole)
Set-AzureADApplication -ObjectId $app.ObjectId -AppRoles $appRoles
完成上述脚本后,即可添加AppRole,然后将角色分配给用户非常简单,并且可以使用直接命令。这是一个示例脚本-
# Assign the values to the variables
$username = "<You user's UPN>"
$app_name = "<Your App's display name>"
$app_role_name = "<App role display name>"
# Get the user to assign, and the service principal for the app to assign to
$user = Get-AzureADUser -ObjectId "$username"
$sp = Get-AzureADServicePrincipal -Filter "displayName eq '$app_name'"
$appRole = $sp.AppRoles | Where-Object { $_.DisplayName -eq $app_role_name }
# Assign the user to the app role
New-AzureADUserAppRoleAssignment -ObjectId $user.ObjectId -PrincipalId $user.ObjectId -ResourceId $sp.ObjectId -Id $appRole.Id