Search code examples
azurepowershellazure-active-directory

Issue using New-MgServicePrincipalAppRoleAssignment in place of New-AzureAdServiceAppRoleAssignment


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:

  • Application.ReadWrite.All
  • AppRoleAssignment.ReadWrite.All
  • DelegatedPermissionGrant.ReadWrite.All

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
  }

Solution

  • I created an Azure AD Application and granted AppRoleAssignment.ReadWrite.All Application permission:

    enter image description here

    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
    

    enter image description here

    The Group.Read.All API permission got assigned successfully to the Service Principal like below:

    enter image description here

    If still the issue persists, check whether you are passing valid resourceId:

    The Application ID with ID 00000003-0000-0000-c000-000000000000

    enter image description here

    • In your case, you are passing ServicePrincipalId as Graph App ID which is invalid, you have to pass the same ID as principalId.
    New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId ServicePrincipalObjectID -BodyParameter $params
    
    • Assign Application API permission to perform the action as you are connecting to MgGraph in the Application context.

    Reference:

    Grant an appRoleAssignment to a service principal