How to add app roles under manifest in Azure Active Directory using Powershell script

前端 未结 1 1396
[愿得一人]
[愿得一人] 2020-12-11 07:06

I have created Azure Active Directory application manually. I want to add user and assign the user roles through PowerShell script.

I am able to add user with the Po

相关标签:
1条回答
  • 2020-12-11 07:45

    You can do this while creating a new app using New-AzureADApplication or for an existing application using Set-AzureADApplication. I don't see a command specifically to add/remove just the roles and that's why the above two options.

    Here's an example PowerShell script for adding a new app role to an existing registered application:

    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
    

    Once you are done with above script to add AppRole, then assigning roles to a user is pretty simple and a direct command is available. Here's a sample script for that -

    # 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
    
    0 讨论(0)
提交回复
热议问题