I need to create powershell code for adding PIM role assignments on azure subscription scope. I have prepared below presented code:
$subscriptionid = "subID"
$tenantId = "tenantID"
$clientId = "ClientID"
$clientSecret = "ClientSecret"
$secureClientSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($clientId, $secureClientSecret)
Connect-AzAccount -ServicePrincipal -Credential $credential -TenantId $tenantId -Subscription $subscriptionid
Connect-MgGraph -TenantID $tenantId -ClientSecretCredential $credential
$auth_token = (Get-AzAccessToken).Token
I am using $auth_token
, my registered application is added to Global Administrator group in EntraID. I am trying to use Microsoft Graph Rest API (MS documentation - Graph rest API documentation). I have code prepared:
$body_json = @"
"roleDefinitionId": "Azure RBAC Contributor role ID",
"resourceId": "My Azure Subscription ID",
"subjectId": "My Entra ID group ID",
"assignmentState": "Eligible",
"type": "AdminAdd",
"schedule": {
"type": "Once",
"startDateTime": "2023-11-12T23:37:43.356Z",
"endDateTime": "2024-11-08T23:37:43.356Z"
}
"@
$response = Invoke-RestMethod -method POST `
-uri "https://graph.microsoft.com/privilegedAccess/azureResources/roleAssignmentRequests" `
-Body $body_json `
-Headers @{"Content-type"="application/json";"Authorization"="Bearer $auth_token"}
Once I run the script I am still facing error code
Invoke-RestMethod: {"error":{"code":"InvalidAuthenticationToken","message":"Access token validation failure. Invalid audience.","innerError":{"date":"2023-10-30T18:29:03","request-id":"cdbbd9ac-aead-4f5f-9e55-8013d4b6a554","client-request-id":"cdbbd9ac-aead-4f5f-9e55-8013d4b6a554"}}}
I assigned the user Privileged role Administrator like below:
And directly use the below script to create role assignments:
If still the issue persists, change azureResources with aadroles as suggested by SaurabhSharma in this SO Thread
I tried to create the governance role assignment request via Rest API with above permissions using access token and roles and the request is successful:
Reference:
Graph api call to make AAD role assignment request not working - Microsoft Q&A by Siva-kumar-selvaraj