Created
June 29, 2023 12:04
-
-
Save mayrund/2a1dd4310b5b02ef2f82ed07a09e201d to your computer and use it in GitHub Desktop.
A script to assign application roles to a user or group in Azure AD.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Parameters | |
$tenantId = "<tenant-id>" | |
$userOrGroupOId = "<user-or-group-id>" | |
$appRegistrationName = "<app-registration-name>" | |
# Connect to Azure AD using the specified tenant ID | |
Connect-AzureAD -TenantId $tenantId > Out-Null | |
# Retrieve the Azure AD application with the specified display name | |
$application = Get-AzureADApplication -All $true | Where-Object {$_.DisplayName -eq $appRegistrationName} | |
# Obtain the object ID of the application | |
$appRegistrationObjectId = $application.ObjectId | |
Write-Host ("Application registration object id is {0}" -f $appRegistrationObjectId) | |
# Retrieve the enterprise application associated with the application ID | |
$enterpriseApplication = Get-AzureADServicePrincipal -Filter "appId eq '$($application.AppId)'" | |
Write-Host ("Enterprise application object id is {0}" -f $enterpriseApplication.ObjectId) | |
# Retrieve the app roles associated with the application | |
$roles = (Get-AzureADApplication -ObjectId $appRegistrationObjectId).AppRoles | |
Write-Host ("Found {0} roles" -f $roles.Count) | |
foreach ($role in $roles) { | |
$roleAssignmentParams = @{ | |
ObjectId = $enterpriseApplication.ObjectId | |
PrincipalId = $userOrGroupOId | |
ResourceId = $enterpriseApplication.ObjectId | |
Id = $role.Id | |
} | |
Write-Host "Adding role" $role.Value | |
try { | |
New-AzureADServiceAppRoleAssignment @roleAssignmentParams | |
} | |
catch { | |
$errorMessage = $_.Exception.Message | |
$duplicatePermissionError = "Permission being assigned already exists on the object" | |
if ($errorMessage -like "*$duplicatePermissionError*") { | |
Write-Host "An error occurred: $duplicatePermissionError" | |
} else { | |
Write-Host "An error occurred: $errorMessage" | |
} | |
$errorOccurred = $true | |
} | |
} | |
if ($errorOccurred) { | |
Write-Host "Errors occurred. Please check above." | |
} else { | |
Write-Host "Roles have been added to the user/group successfully." | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment