I am trying to add a graph API role in PowerShell and getting the following generic error when using graph instead of AzureAD module.
Error:
"One or more errors occurred"
InnerException: System.ObjectDisposedException: Cannot access a disposed object.
The service principal I am connecting with has the following delegated permissions with admin consent:
Code:
$ApplicationId = '<Myappid>'
$SecuredPassword = '<MyAppID secret>'
$tenantID = '<MyTenantID>'
$SecuredPasswordPassword = ConvertTo-SecureString -String $SecuredPassword -AsPlainText -Force
$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationId, $SecuredPasswordPassword
Connect-MgGraph -TenantId $tenantID -ClientSecretCredential $ClientSecretCredential
$params = @{
"PrincipalId" = "<principalID>" #ObjectID of the enterprise app for my app registration
"ResourceId" = "resourceID" #ID of graph service principal ID in my tenant
"AppRoleId" = "approleID" #ID of the graph role
}
try {
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId "<same as resource ID in params; Graph api id>" -BodyParameter $params -ErrorAction:Stop
}
catch {
$tmpError = $_.exception
}
I created an Azure AD Application and granted AppRoleAssignment.ReadWrite.All
Application permission:
To assign Graph role to the Service Principal, make use of below PowerShell script:
$ApplicationId = "AppID"
$tenantID = "TenantID"
Connect-MgGraph -ClientId $ApplicationId -TenantId $tenantID -CertificateThumbprint "xxxxx"
$params = @{
principalId = "ServicePrincipalObjectID"
resourceId = "MicrosoftGraphObjectID"
appRoleId = "5b567255-7703-4780-807c-7be8301ae99b"
}
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId ServicePrincipalObjectID -BodyParameter $params
The Group.Read.All
API permission got assigned successfully to the Service Principal like below:
If still the issue persists, check whether you are passing valid resourceId
:
The Application ID with ID 00000003-0000-0000-c000-000000000000
ServicePrincipalId
as Graph App ID which is invalid, you have to pass the same ID as principalId
.New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId ServicePrincipalObjectID -BodyParameter $params
MgGraph
in the Application context.Reference: