Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.25k stars 3.85k forks source link

New-AzRoleAssignment not working with ServicePrincipal #16319

Closed Agazoth closed 2 years ago

Agazoth commented 2 years ago

Description

Running New-AzRoleAssignment in the context of a ServicePrincipal targeting a resource group on a subscription the Service Principal has Owner rights on fails.

Steps to reproduce

$credential = Get-Credential # Apply applicationId and ApplicationSecret of the ServicePrincipal
$tenantId = 'e8351e33-2fca-45d3-9859-97b6ad429db9' # Your tenant id
$subscriptionId = 'cc0ff6ae-b1dc-4a0f-9c21-4e262831c2b5' # Your subscription id
$resourceGroupName = 'rg'test'rbac'
$groupObjectId = '50d2e252-1c34-440f-9eee-54e827fa84ef'
Connect-AzAccount -ServicePrincipal -Credential $credential -TenantId $tenantId -SubscriptionId $subscriptionId

New-AzRoleAssignment -ObjectId $groupObjectId -RoleDefinitionName Reader -ResourceGroupName $resourceGroupName

New-AzRoleAssignment: Exception of type 'Microsoft.Rest.Azure.CloudException' was thrown.

Running the same command when connected with a user account with owner rights on the subscription does not produce this error.

Environment data

Tis error persists both on my dev box and in DevOps MS hosted pipelines ubuntulatest. Details here is from my dev box.

Name                           Value
----                           -----
PSVersion                      7.1.5
PSEdition                      Core
GitCommitId                    7.1.5
OS                             Microsoft Windows 10.0.22000
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Module versions


    Directory: C:\Users\axel\Documents\PowerShell\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Manifest   1.3.0                 AxKeyVault                          Desk      
Script     6.4.0                 Az                                  Core,Desk 
Script     2.5.3                 Az.Accounts                         Core,Desk {Disable-AzDataCollection, Disable-AzCon…
Script     1.1.1                 Az.Advisor                          Core,Desk {Get-AzAdvisorRecommendation, Enable-AzA…
Script     2.4.0                 Az.Aks                              Core,Desk {Get-AzAksCluster, New-AzAksCluster, Rem…
Script     1.1.4                 Az.AnalysisServices                 Core,Desk {Resume-AzAnalysisServicesServer, Suspen…
Script     2.3.0                 Az.ApiManagement                    Core,Desk {Add-AzApiManagementApiToGateway, Add-Az…
Script     1.0.0                 Az.AppConfiguration                 Core,Desk {Get-AzAppConfigurationStore, Get-AzAppC…
Script     1.2.0                 Az.ApplicationInsights              Core,Desk {Get-AzApplicationInsights, New-AzApplic…
Script     1.7.1                 Az.Automation                       Core,Desk {Get-AzAutomationHybridWorkerGroup, Remo…
Script     3.1.0                 Az.Batch                            Core,Desk {Remove-AzBatchAccount, Get-AzBatchAccou…
Script     2.0.0                 Az.Billing                          Core,Desk {Get-AzBillingInvoice, Get-AzBillingPeri…
Script     1.8.0                 Az.Cdn                              Core,Desk {Get-AzCdnProfile, Get-AzCdnProfileSsoUr…
Script     1.9.0                 Az.CognitiveServices                Core,Desk {Get-AzCognitiveServicesAccount, Get-AzC…
Script     4.17.0                Az.Compute                          Core,Desk {Remove-AzAvailabilitySet, Get-AzAvailab…
Script     2.1.0                 Az.ContainerInstance                Core,Desk {Add-AzContainerInstanceOutput, Get-AzCo…
Script     2.2.3                 Az.ContainerRegistry                Core,Desk {New-AzContainerRegistry, Get-AzContaine…
Script     1.3.1                 Az.CosmosDB                         Core,Desk {Get-AzCosmosDBSqlContainer, Get-AzCosmo…
Script     1.1.0                 Az.DataBoxEdge                      Core,Desk {Get-AzDataBoxEdgeJob, Get-AzDataBoxEdge…
Script     1.1.0                 Az.Databricks                       Core,Desk {Get-AzDatabricksVNetPeering, Get-AzData…
Script     1.14.0                Az.DataFactory                      Core,Desk {Set-AzDataFactoryV2, Update-AzDataFacto…
Script     1.0.2                 Az.DataLakeAnalytics                Core,Desk {Get-AzDataLakeAnalyticsDataSource, New-…
Script     1.3.0                 Az.DataLakeStore                    Core,Desk {Get-AzDataLakeStoreTrustedIdProvider, R…
Script     1.0.0                 Az.DataShare                        Core,Desk {New-AzDataShareAccount, Get-AzDataShare…
Script     1.1.0                 Az.DeploymentManager                Core,Desk {Get-AzDeploymentManagerArtifactSource, …
Script     3.0.0                 Az.DesktopVirtualization            Core,Desk {Disconnect-AzWvdUserSession, Expand-AzW…
Script     1.0.2                 Az.DevTestLabs                      Core,Desk {Get-AzDtlAllowedVMSizesPolicy, Get-AzDt…
Script     1.1.2                 Az.Dns                              Core,Desk {Get-AzDnsRecordSet, New-AzDnsRecordConf…
Script     1.3.0                 Az.EventGrid                        Core,Desk {New-AzEventGridTopic, Get-AzEventGridTo…
Script     1.8.0                 Az.EventHub                         Core,Desk {New-AzEventHubNamespace, Get-AzEventHub…
Script     1.8.0                 Az.FrontDoor                        Core,Desk {New-AzFrontDoor, Get-AzFrontDoor, Set-A…
Script     3.1.0                 Az.Functions                        Core,Desk {Get-AzFunctionApp, Get-AzFunctionAppAva…
Script     4.3.0                 Az.HDInsight                        Core,Desk {Get-AzHDInsightJob, New-AzHDInsightSqoo…
Script     1.3.1                 Az.HealthcareApis                   Core,Desk {New-AzHealthcareApisService, Remove-AzH…
Script     2.7.3                 Az.IotHub                           Core,Desk {Add-AzIotHubKey, Get-AzIotHubEventHubCo…
Script     3.5.0                 Az.KeyVault                         Core,Desk {Add-AzKeyVaultCertificate, Update-AzKey…
Script     2.0.0                 Az.Kusto                            Core,Desk {Add-AzKustoClusterLanguageExtension, Ad…
Script     1.5.0                 Az.LogicApp                         Core,Desk {Get-AzIntegrationAccountAgreement, Get-…
Script     1.1.3                 Az.MachineLearning                  Core,Desk {Move-AzMlCommitmentAssociation, Get-AzM…
Script     1.1.1                 Az.Maintenance                      Core,Desk {Get-AzApplyUpdate, Get-AzConfigurationA…
Script     0.7.3                 Az.ManagedServiceIdentity           Core,Desk {New-AzUserAssignedIdentity, Get-AzUserA…
Script     2.0.0                 Az.ManagedServices                  Core,Desk {Get-AzManagedServicesAssignment, New-Az…
Script     1.0.2                 Az.MarketplaceOrdering              Core,Desk {Get-AzMarketplaceTerms, Set-AzMarketpla…
Script     1.1.1                 Az.Media                            Core,Desk {Sync-AzMediaServiceStorageKey, Set-AzMe…
Script     1.1.1                 Az.Migrate                          Core,Desk {Get-AzMigrateDiscoveredServer, Get-AzMi…
Script     2.7.0                 Az.Monitor                          Core,Desk {Get-AzMetricDefinition, Get-AzMetric, R…
Script     4.11.0                Az.Network                          Core,Desk {Add-AzApplicationGatewayAuthenticationC…
Script     1.1.1                 Az.NotificationHubs                 Core,Desk {Get-AzNotificationHub, Get-AzNotificati…
Script     2.3.0                 Az.OperationalInsights              Core,Desk {New-AzOperationalInsightsAzureActivityL…
Script     1.4.1                 Az.PolicyInsights                   Core,Desk {Get-AzPolicyEvent, Get-AzPolicyState, G…
Script     1.1.2                 Az.PowerBIEmbedded                  Core,Desk {Remove-AzPowerBIWorkspaceCollection, Ge…
Script     1.0.3                 Az.PrivateDns                       Core,Desk {Get-AzPrivateDnsZone, Remove-AzPrivateD…
Script     4.6.0                 Az.RecoveryServices                 Core,Desk {Get-AzRecoveryServicesBackupProperty, G…
Script     1.5.0                 Az.RedisCache                       Core,Desk {Remove-AzRedisCachePatchSchedule, New-A…
Script     1.0.0                 Az.RedisEnterpriseCache             Core,Desk {Export-AzRedisEnterpriseCache, Get-AzRe…
Script     1.0.3                 Az.Relay                            Core,Desk {New-AzRelayNamespace, Get-AzRelayNamesp…
Script     1.0.0                 Az.ResourceMover                    Core,Desk {Add-AzResourceMoverMoveResource, Get-Az…
Script     4.3.1                 Az.Resources                        Core,Desk {Get-AzProviderOperation, Remove-AzRoleA…
Script     1.0.0                 Az.Security                         Core,Desk {Get-AzSecurityAlert, Set-AzSecurityAler…
Script     1.1.0                 Az.SecurityInsights                 Core,Desk {Get-AzSentinelAlertRuleAction, New-AzSe…
Script     1.5.0                 Az.ServiceBus                       Core,Desk {New-AzServiceBusNamespace, Get-AzServic…
Script     3.0.1                 Az.ServiceFabric                    Core,Desk {Add-AzServiceFabricClientCertificate, A…
Script     1.3.0                 Az.SignalR                          Core,Desk {New-AzSignalR, Get-AzSignalR, Get-AzSig…
Script     3.5.0                 Az.Sql                              Core,Desk {Get-AzSqlDatabaseTransparentDataEncrypt…
Script     1.1.0                 Az.SqlVirtualMachine                Core,Desk {New-AzSqlVM, Get-AzSqlVM, Update-AzSqlV…
Script     3.11.0                Az.Storage                          Core,Desk {Get-AzStorageAccount, Get-AzStorageAcco…
Script     1.6.0                 Az.StorageSync                      Core,Desk {Invoke-AzStorageSyncCompatibilityCheck,…
Script     2.0.0                 Az.StreamAnalytics                  Core,Desk {Get-AzStreamAnalyticsCluster, Get-AzStr…
Script     1.0.0                 Az.Support                          Core,Desk {Get-AzSupportService, Get-AzSupportProb…
Script     1.0.4                 Az.TrafficManager                   Core,Desk {Add-AzTrafficManagerCustomHeaderToEndpo…
Script     2.8.2                 Az.Websites                         Core,Desk {Get-AzAppServicePlan, Set-AzAppServiceP…
Binary     2.0.2.138             AzureADPreview                      Desk      
Binary     2.0.2.136             AzureADPreview                      Desk      
Manifest   1.6.1                 Microsoft.Graph                     Core,Desk 
Script     1.6.1                 Microsoft.Graph.Applications        Core,Desk {Add-MgApplicationKey, Add-MgApplication…
Script     1.6.0                 Microsoft.Graph.Authentication      Core,Desk {Connect-MgGraph, Disconnect-MgGraph, Ge…
Script     1.6.0                 Microsoft.Graph.Bookings            Core,Desk {Get-MgBookingBusiness, Get-MgBookingBus…
Script     1.6.0                 Microsoft.Graph.Calendar            Core,Desk {Get-MgGroupCalendar, Get-MgGroupCalenda…
Script     1.6.0                 Microsoft.Graph.ChangeNotifications Core,Desk {Get-MgSubscription, New-MgSubscription,…
Script     1.6.1                 Microsoft.Graph.CloudCommunications Core,Desk {Clear-MgCommunicationPresence, Get-MgCo…
Script     1.6.1                 Microsoft.Graph.Compliance          Core,Desk {Add-MgComplianceEdiscoveryCaseReviewSet…
Script     1.6.0                 Microsoft.Graph.CrossDeviceExperie… Core,Desk {Get-MgUserActivity, Get-MgUserActivityH…
Script     1.6.1                 Microsoft.Graph.DeviceManagement    Core,Desk {Get-MgDeviceManagement, Get-MgDeviceMan…
Script     1.6.1                 Microsoft.Graph.DeviceManagement.A… Core,Desk {Add-MgDeviceManagementGroupPolicyUpload…
Script     1.6.1                 Microsoft.Graph.DeviceManagement.A… Core,Desk {Get-MgDeviceManagementApplePushNotifica…
Script     1.6.0                 Microsoft.Graph.DeviceManagement.E… Core,Desk {Get-MgDeviceManagementAndroid, Get-MgDe…
Script     1.6.0                 Microsoft.Graph.DeviceManagement.F… Core,Desk {Compare-MgDeviceManagementIntent, Compa…
Script     1.6.1                 Microsoft.Graph.Devices.CloudPrint  Core,Desk {Get-MgPrint, Get-MgPrintConnector, Get-…
Script     1.6.1                 Microsoft.Graph.Devices.CorporateM… Core,Desk {Clear-MgDeviceAppMgtWindowInformationPr…
Script     1.6.0                 Microsoft.Graph.DirectoryObjects    Core,Desk {Confirm-MgDirectoryObjectMemberGroup, C…
Script     1.6.1                 Microsoft.Graph.Education           Core,Desk {Get-MgEducationClass, Get-MgEducationCl…
Script     1.6.1                 Microsoft.Graph.Files               Core,Desk {Add-MgDriveListContentTypeBaseTypeCopy,…
Script     1.6.0                 Microsoft.Graph.Financials          Core,Desk {Get-MgFinancial, Get-MgFinancialCompany…
Script     1.6.1                 Microsoft.Graph.Groups              Core,Desk {Add-MgGroupFavorite, Add-MgGroupToLifec…
Script     1.6.1                 Microsoft.Graph.Identity.Directory… Core,Desk {Confirm-MgAdministrativeUnitMemberGroup…
Script     1.6.1                 Microsoft.Graph.Identity.Governance Core,Desk {Add-MgAccessReviewDecision, Get-MgAcces…
Script     1.6.1                 Microsoft.Graph.Identity.SignIns    Core,Desk {Confirm-MgRiskyUserCompromised, Get-MgD…
Script     1.6.0                 Microsoft.Graph.Mail                Core,Desk {Get-MgUserInferenceClassification, Get-…
Script     1.6.0                 Microsoft.Graph.Notes               Core,Desk {Get-MgGroupOnenoteNotebook, Get-MgGroup…
Script     1.6.0                 Microsoft.Graph.People              Core,Desk {Get-MgUserActivityStatistics, Get-MgUse…
Script     1.6.0                 Microsoft.Graph.PersonalContacts    Core,Desk {Get-MgUserContact, Get-MgUserContactExt…
Script     1.6.0                 Microsoft.Graph.Planner             Core,Desk {Get-MgGroupPlanner, Get-MgGroupPlannerP…
Script     1.6.0                 Microsoft.Graph.Reports             Core,Desk {Get-MgAuditLogDirectoryAudit, Get-MgAud…
Script     1.6.0                 Microsoft.Graph.SchemaExtensions    Core,Desk {Get-MgSchemaExtension, New-MgSchemaExte…
Script     1.6.1                 Microsoft.Graph.Search              Core,Desk {Get-MgExternal, Get-MgExternalConnectio…
Script     1.6.1                 Microsoft.Graph.Security            Core,Desk {Get-MgSecurityAction, Get-MgSecurityAle…
Script     1.6.1                 Microsoft.Graph.Sites               Core,Desk {Add-MgSiteContentTypeBaseTypeCopy, Add-…
Script     1.6.1                 Microsoft.Graph.Teams               Core,Desk {Add-MgChatMember, Add-MgTeamChannelMemb…
Script     1.6.1                 Microsoft.Graph.Users               Core,Desk {Get-MgUser, Get-MgUserCreatedObject, Ge…
Script     1.6.1                 Microsoft.Graph.Users.Actions       Core,Desk {Add-MgUserInsightSharedLastSharedMethod…
Script     1.6.1                 Microsoft.Graph.Users.Functions     Core,Desk {Export-MgUserDeviceAndAppManagementData…
Script     1.6.0                 Microsoft.Graph.WindowsUpdates      Core,Desk {Add-MgWindowsUpdatesDeploymentAudienceM…
Binary     0.6.2                 Microsoft.PowerShell.ConsoleGuiToo… Core      {Out-ConsoleGridView, ocgv}
Binary     1.1.0                 Microsoft.PowerShell.SecretManagem… Core      {Register-SecretVault, Unregister-Secret…
Binary     1.0.3                 Microsoft.PowerShell.SecretStore    Core      {Unlock-SecretStore, Set-SecretStorePass…
Script     21.0.7930…            ParquetCmdlets                      Desk      {Remove-Parquet, Connect-Parquet, Add-Pa…
Script     5.3.0                 Pester                              Desk      {Invoke-Pester, Describe, Context, It…}
Script     1.1.3                 Plaster                             Desk      {Invoke-Plaster, New-PlasterManifest, Ge…
Script     0.14.2                platyPS                             Desk      {New-MarkdownHelp, Get-MarkdownMetadata,…
Script     2.4.1                 Pode                                Desk      {Get-PodeCookie, Get-PodeCookieSecret, R…
Script     0.6.0                 Pode.Web                            Desk      {Show-PodeWebNotification, New-PodeWebTa…
Script     1.0.0                 posh-git                            Desk      {Add-PoshGitToProfile, Expand-GitCommand…
Script     4.9.0                 psake                               Desk      {Invoke-psake, Invoke-Task, Get-PSakeScr…
Script     2.2.0      beta3      PSReadLine                          Desk      {Get-PSReadLineKeyHandler, Set-PSReadLin…
Script     21.1.18256            SqlServer                           Desk      {Add-RoleMember, Add-SqlAvailabilityData…
Script     0.5.2                 Terminal-Icons                      Desk      {Add-TerminalIconsColorTheme, Add-Termin…

    Directory: C:\program files\powershell\7\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Manifest   7.0.0.0               CimCmdlets                          Core      {Get-CimAssociatedInstance, Get-CimClass…
Manifest   1.2.5                 Microsoft.PowerShell.Archive        Desk      {Compress-Archive, Expand-Archive}
Manifest   7.0.0.0               Microsoft.PowerShell.Diagnostics    Core      {Get-WinEvent, New-WinEvent, Get-Counter}
Manifest   7.0.0.0               Microsoft.PowerShell.Host           Core      {Start-Transcript, Stop-Transcript}
Manifest   7.0.0.0               Microsoft.PowerShell.Management     Core      {Add-Content, Clear-Content, Get-Clipboa…
Manifest   7.0.0.0               Microsoft.PowerShell.Security       Core      {Get-Acl, Set-Acl, Get-PfxCertificate, G…
Manifest   7.0.0.0               Microsoft.PowerShell.Utility        Core      {Export-Alias, Get-Alias, Import-Alias, …
Manifest   7.0.0.0               Microsoft.WSMan.Management          Core      {Disable-WSManCredSSP, Enable-WSManCredS…
Script     1.4.7                 PackageManagement                   Desk      {Find-Package, Get-Package, Get-PackageP…
Script     2.2.5                 PowerShellGet                       Desk      {Find-Command, Find-DSCResource, Find-Mo…
Script     2.0.5                 PSDesiredStateConfiguration         Core      {Configuration, New-DscChecksum, Get-Dsc…
Script     7.0.0.0               PSDiagnostics                       Core      {Disable-PSTrace, Disable-PSWSManCombine…
Script     2.1.0                 PSReadLine                          Desk      {Get-PSReadLineKeyHandler, Set-PSReadLin…
Binary     2.0.3                 ThreadJob                           Desk      Start-ThreadJob

    Directory: C:\Program Files\WindowsPowerShell\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Script     5.1.2                 Azure                               Desk      {Get-AzureAutomationCertificate, Get-Azu…
Manifest   0.5.0                 Azure.AnalysisServices              Desk      {Add-AzureAnalysisServicesAccount, Resta…
Script     4.2.1                 Azure.Storage                       Desk      {Get-AzureStorageTable, New-AzureStorage…
Script     5.7.0                 AzureRM                             Desk      
Script     0.6.6                 AzureRM.AnalysisServices            Desk      {Resume-AzureRmAnalysisServicesServer, S…
Script     5.1.2                 AzureRM.ApiManagement               Desk      {Add-AzureRmApiManagementRegion, Get-Azu…
Script     0.1.3                 AzureRM.ApplicationInsights         Desk      {Get-AzureRmApplicationInsights, New-Azu…
Script     4.3.2                 AzureRM.Automation                  Desk      {Get-AzureRMAutomationHybridWorkerGroup,…
Script     4.0.4                 AzureRM.Backup                      Desk      {Backup-AzureRmBackupItem, Enable-AzureR…
Script     4.0.6                 AzureRM.Batch                       Desk      {Remove-AzureRmBatchAccount, Get-AzureRm…
Script     0.14.1                AzureRM.Billing                     Desk      {Get-AzureRmBillingInvoice, Get-AzureRmB…
Script     4.2.2                 AzureRM.Cdn                         Desk      {Get-AzureRmCdnProfile, Get-AzureRmCdnPr…
Script     0.9.4                 AzureRM.CognitiveServices           Desk      {Get-AzureRmCognitiveServicesAccount, Ge…
Script     4.6.0                 AzureRM.Compute                     Desk      {Remove-AzureRmAvailabilitySet, Get-Azur…
Script     0.3.1                 AzureRM.Consumption                 Desk      Get-AzureRmConsumptionUsageDetail
Script     0.2.5                 AzureRM.ContainerInstance           Desk      {New-AzureRmContainerGroup, Get-AzureRmC…
Script     1.0.4                 AzureRM.ContainerRegistry           Desk      {New-AzureRmContainerRegistry, Get-Azure…
Script     4.2.2                 AzureRM.DataFactories               Desk      {Remove-AzureRmDataFactory, Get-AzureRmD…
Script     0.5.3                 AzureRM.DataFactoryV2               Desk      {Set-AzureRmDataFactoryV2, Update-AzureR…
Script     4.2.3                 AzureRM.DataLakeAnalytics           Desk      {Get-AzureRmDataLakeAnalyticsDataSource,…
Script     5.2.0                 AzureRM.DataLakeStore               Desk      {Get-AzureRmDataLakeStoreTrustedIdProvid…
Script     4.0.4                 AzureRM.DevTestLabs                 Desk      {Get-AzureRmDtlAllowedVMSizesPolicy, Get…
Script     4.1.2                 AzureRM.Dns                         Desk      {Get-AzureRmDnsRecordSet, New-AzureRmDns…
Script     0.3.2                 AzureRM.EventGrid                   Desk      {New-AzureRmEventGridTopic, Get-AzureRmE…
Script     0.6.3                 AzureRM.EventHub                    Desk      {New-AzureRmEventHubNamespace, Get-Azure…
Script     4.1.2                 AzureRM.HDInsight                   Desk      {Get-AzureRmHDInsightJob, New-AzureRmHDI…
Script     4.0.4                 AzureRM.Insights                    Desk      {Get-AzureRmMetricDefinition, Get-AzureR…
Script     3.1.2                 AzureRM.IotHub                      Desk      {Add-AzureRmIotHubKey, Get-AzureRmIotHub…
Script     4.3.0                 AzureRM.KeyVault                    Desk      {Add-AzureKeyVaultCertificate, Set-Azure…
Script     4.0.3                 AzureRM.LogicApp                    Desk      {Get-AzureRmIntegrationAccountAgreement,…
Script     0.17.2                AzureRM.MachineLearning             Desk      {Move-AzureRmMlCommitmentAssociation, Ge…
Script     0.4.2                 AzureRM.MachineLearningCompute      Desk      {Get-AzureRmMlOpCluster, Get-AzureRmMlOp…
Script     0.2.1                 AzureRM.MarketplaceOrdering         Desk      {Get-AzureRmMarketplaceTerms, Set-AzureR…
Script     0.9.2                 AzureRM.Media                       Desk      {Sync-AzureRmMediaServiceStorageKeys, Se…
Script     5.4.2                 AzureRM.Network                     Desk      {Add-AzureRmApplicationGatewayAuthentica…
Script     4.1.1                 AzureRM.NotificationHubs            Desk      {Get-AzureRmNotificationHub, Get-AzureRm…
Script     4.3.2                 AzureRM.OperationalInsights         Desk      {New-AzureRmOperationalInsightsAzureActi…
Script     4.1.4                 AzureRM.PowerBIEmbedded             Desk      {Remove-AzureRmPowerBIWorkspaceCollectio…
Script     4.6.0                 AzureRM.Profile                     Desk      {Disable-AzureRmDataCollection, Disable-…
Script     4.1.2                 AzureRM.RecoveryServices            Desk      {Get-AzureRmRecoveryServicesBackupProper…
Script     4.1.2                 AzureRM.RecoveryServices.Backup     Desk      {Backup-AzureRmRecoveryServicesBackupIte…
Script     0.2.4                 AzureRM.RecoveryServices.SiteRecov… Desk      {Edit-AzureRmRecoveryServicesAsrRecovery…
Script     4.1.2                 AzureRM.RedisCache                  Desk      {Remove-AzureRmRedisCachePatchSchedule, …
Script     0.3.3                 AzureRM.Relay                       Desk      {New-AzureRmRelayNamespace, Get-AzureRmR…
Script     5.5.2                 AzureRM.Resources                   Desk      {Get-AzureRmProviderOperation, Remove-Az…
Script     0.16.3                AzureRM.Scheduler                   Desk      {Disable-AzureRmSchedulerJobCollection, …
Script     4.1.2                 AzureRM.ServerManagement            Desk      {Invoke-AzureRmServerManagementPowerShel…
Script     0.6.4                 AzureRM.ServiceBus                  Desk      {New-AzureRmServiceBusNamespace, Get-Azu…
Script     0.3.4                 AzureRM.ServiceFabric               Desk      {Add-AzureRmServiceFabricApplicationCert…
Script     5.0.6                 AzureRM.SiteRecovery                Desk      {Get-AzureRmSiteRecoveryFabric, New-Azur…
Script     4.4.0                 AzureRM.Sql                         Desk      {Get-AzureRmSqlDatabaseTransparentDataEn…
Script     4.2.3                 AzureRM.Storage                     Desk      {Get-AzureRmStorageAccount, Get-AzureRmS…
Script     4.0.4                 AzureRM.StreamAnalytics             Desk      {Get-AzureRmStreamAnalyticsFunction, Get…
Script     4.0.1                 AzureRM.Tags                        Desk      {Remove-AzureRmTag, Get-AzureRmTag, New-…
Script     4.0.3                 AzureRM.TrafficManager              Desk      {Disable-AzureRmTrafficManagerEndpoint, …
Script     4.0.2                 AzureRM.UsageAggregates             Desk      Get-UsageAggregates
Script     4.2.2                 AzureRM.Websites                    Desk      {Get-AzureRmAppServicePlan, Set-AzureRmA…
Script     1.0.1                 Microsoft.PowerShell.Operation.Val… Desk      {Get-OperationValidation, Invoke-Operati…
Binary     1.0.0.1               PackageManagement                   Desk      {Find-Package, Get-Package, Get-PackageP…
Script     3.0.10                PartnerCenter                       Core,Desk {Add-PartnerCustomerCartLineItem, Add-Pa…
Script     3.4.0                 Pester                              Desk      {Describe, Context, It, Should…}
Script     1.0.0.1               PowerShellGet                       Desk      {Install-Module, Find-Module, Save-Modul…

    Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version    PreRelease Name                                PSEdition ExportedCommands
---------- -------    ---------- ----                                --------- ----------------
Manifest   1.0.0.0               AppBackgroundTask                   Core,Desk {Disable-AppBackgroundTaskDiagnosticLog,…
Manifest   2.0.1.0               Appx                                Core,Desk {Add-AppxPackage, Get-AppxPackage, Get-A…
Script     1.0.0.0               AssignedAccess                      Core,Desk {Clear-AssignedAccess, Get-AssignedAcces…
Manifest   1.0.0.0               BitLocker                           Core,Desk {Unlock-BitLocker, Suspend-BitLocker, Re…
Manifest   2.0.0.0               BitsTransfer                        Core,Desk {Add-BitsFile, Complete-BitsTransfer, Ge…
Manifest   1.0.0.0               BranchCache                         Core,Desk {Add-BCDataCacheExtension, Clear-BCCache…
Manifest   1.0.3.0               DeliveryOptimization                Core,Desk {Get-DeliveryOptimizationLog, Get-Delive…
Manifest   1.0.0.0               DirectAccessClientComponents        Core,Desk {Disable-DAManualEntryPointSelection, En…
Script     3.0                   Dism                                Core,Desk {Add-AppProvisionedSharedPackageContaine…
Manifest   1.0.0.0               DnsClient                           Core,Desk {Resolve-DnsName, Clear-DnsClientCache, …
Manifest   1.0.0.0               EventTracingManagement              Core,Desk {Start-EtwTraceSession, New-EtwTraceSess…
Script     2021.3.23…            Get-NetView                         Core,Desk Get-NetView
Manifest   2.1.0.0               International                       Core,Desk {Copy-UserInternationalSettingsToSystem,…
Manifest   1.0.0.0               Kds                                 Core,Desk {Add-KdsRootKey, Get-KdsRootKey, Test-Kd…
Manifest   3.0.0.0               Microsoft.PowerShell.Diagnostics    Core,Desk {Get-WinEvent, Get-Counter, Import-Count…
Manifest   1.0.0.0               Microsoft.PowerShell.LocalAccounts  Core,Desk {Add-LocalGroupMember, Disable-LocalUser…
Manifest   1.0.0                 Microsoft.Windows.Bcd.Cmdlets       Core,Desk {Copy-BcdEntry, Disable-BcdElementBootDe…
Manifest   1.0                   MMAgent                             Core,Desk {Disable-MMAgent, Enable-MMAgent, Set-MM…
Manifest   2.0.0.0               NetAdapter                          Core,Desk {Disable-NetAdapter, Disable-NetAdapterB…
Manifest   1.0.0.0               NetConnection                       Core,Desk {Get-NetConnectionProfile, Set-NetConnec…
Manifest   1.0.0.0               NetEventPacketCapture               Core,Desk {New-NetEventSession, Remove-NetEventSes…
Manifest   2.0.0.0               NetLbfo                             Core,Desk {Add-NetLbfoTeamMember, Add-NetLbfoTeamN…
Manifest   1.0.0.0               NetNat                              Core,Desk {Get-NetNat, Get-NetNatExternalAddress, …
Manifest   2.0.0.0               NetQos                              Core,Desk {Get-NetQosPolicy, Set-NetQosPolicy, Rem…
Manifest   2.0.0.0               NetSecurity                         Core,Desk {Get-DAPolicyChange, New-NetIPsecAuthPro…
Manifest   1.0.0.0               NetSwitchTeam                       Core,Desk {New-NetSwitchTeam, Remove-NetSwitchTeam…
Manifest   1.0.0.0               NetTCPIP                            Core,Desk {Get-NetIPAddress, Get-NetIPInterface, G…
Manifest   1.0.0.0               NetworkConnectivityStatus           Core,Desk {Get-DAConnectionStatus, Get-NCSIPolicyC…
Manifest   1.0.0.0               NetworkSwitchManager                Core,Desk {Disable-NetworkSwitchEthernetPort, Enab…
Manifest   1.0.0.0               NetworkTransition                   Core,Desk {Add-NetIPHttpsCertBinding, Disable-NetD…
Manifest   1.0.0.0               PcsvDevice                          Core,Desk {Get-PcsvDevice, Start-PcsvDevice, Stop-…
Manifest   1.0.0.0               PKI                                 Core,Desk {Add-CertificateEnrollmentPolicyServer, …
Manifest   1.0.0.0               PnpDevice                           Core,Desk {Get-PnpDevice, Get-PnpDeviceProperty, E…
Manifest   1.1                   PrintManagement                     Core,Desk {Add-Printer, Add-PrinterDriver, Add-Pri…
Binary     1.0.12                ProcessMitigations                  Core,Desk {Get-ProcessMitigation, Set-ProcessMitig…
Script     3.0                   Provisioning                        Core,Desk {Install-ProvisioningPackage, Export-Pro…
Manifest   1.0.0.0               ScheduledTasks                      Core,Desk {Get-ScheduledTask, Set-ScheduledTask, R…
Manifest   2.0.0.0               SecureBoot                          Core,Desk {Confirm-SecureBootUEFI, Set-SecureBootU…
Manifest   2.0.0.0               SmbShare                            Core,Desk {Get-SmbShare, Remove-SmbShare, Set-SmbS…
Manifest   2.0.0.0               SmbWitness                          Core,Desk {Get-SmbWitnessClient, Move-SmbWitnessCl…
Manifest   1.0.0.1               StartLayout                         Core,Desk {Export-StartLayout, Import-StartLayout,…
Manifest   2.0.0.0               Storage                             Core,Desk {Add-InitiatorIdToMaskingSet, Add-Partit…
Manifest   2.0.0.0               TLS                                 Core,Desk {New-TlsSessionTicketKey, Enable-TlsSess…
Manifest   1.0.0.0               TroubleshootingPack                 Core,Desk {Get-TroubleshootingPack, Invoke-Trouble…
Manifest   2.0.0.0               TrustedPlatformModule               Core,Desk {Get-Tpm, Initialize-Tpm, Clear-Tpm, Unb…
Binary     2.1.639.0             UEV                                 Core,Desk 
Manifest   2.0.0.0               VpnClient                           Core,Desk {Add-VpnConnection, Set-VpnConnection, R…
Manifest   1.0.0.0               Wdac                                Core,Desk {Get-OdbcDriver, Set-OdbcDriver, Get-Odb…
Manifest   2.0.0.0               Whea                                Core,Desk {Get-WheaMemoryPolicy, Set-WheaMemoryPol…
Manifest   1.0.0.0               WindowsDeveloperLicense             Core,Desk {Get-WindowsDeveloperLicense, Unregister…
Script     1.0                   WindowsErrorReporting               Core,Desk {Enable-WindowsErrorReporting, Disable-W…
Manifest   1.0.0.0               WindowsSearch                       Core,Desk {Get-WindowsSearchSetting, Set-WindowsSe…
Manifest   1.0.0.0               WindowsUpdate                       Core,Desk Get-WindowsUpdateLog

Debug output

DEBUG: 07:07:20 - NewAzureRoleAssignmentCommand begin processing with ParameterSet 'ResourceGroupWithObjectIdParameterSet'.
DEBUG: 07:07:20 - using account id 'c9b6dd3e-34c5-403a-8097-b9e41571f040'...
DEBUG: [Common.Authentication]: Authenticating using Account: 'c9b6dd3e-34c5-403a-8097-b9e41571f040', environment: 'AzureCloud', tenant: 'e8351e33-2fca-45d3-9859-97b6ad429db9'
DEBUG: 07:07:20 - [ServicePrincipalAuthenticator] Calling ClientSecretCredential.GetTokenAsync - ApplicationId:'c9b6dd3e-34c5-403a-8097-b9e41571f040', TenantId:'e8351e33-2fca-45d3-9859-97b6ad429db9', Scopes:'https://graph.windows.net//.default', AuthorityHost:'https://login.microsoftonline.com/'
DEBUG: ClientSecretCredential.GetToken invoked. Scopes: [ https://graph.windows.net//.default ] ParentRequestId:
DEBUG: Request [65f718e2-0356-429d-87ea-d755fbe3907b] POST https://login.microsoftonline.com/e8351e33-2fca-45d3-9859-97b6ad429db9/oauth2/v2.0/token
x-client-SKU:REDACTED
x-client-Ver:REDACTED
x-client-CPU:REDACTED
x-client-OS:REDACTED
x-client-current-telemetry:REDACTED
x-client-last-telemetry:REDACTED
x-ms-lib-capability:REDACTED
client-request-id:REDACTED
return-client-request-id:REDACTED
x-app-name:REDACTED
x-app-ver:REDACTED
x-ms-client-request-id:65f718e2-0356-429d-87ea-d755fbe3907b
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.4.0,(.NET 5.0.11; Microsoft Windows 10.0.22000)
Content-Type:application/x-www-form-urlencoded
client assembly: Azure.Identity
DEBUG: Response [65f718e2-0356-429d-87ea-d755fbe3907b] 200 OK (00.3s)
Cache-Control:no-store, no-cache
Pragma:no-cache
Strict-Transport-Security:REDACTED
X-Content-Type-Options:REDACTED
P3P:REDACTED
client-request-id:REDACTED
x-ms-request-id:539b8238-91c4-4631-a5df-23f52bd48e00
x-ms-ests-server:REDACTED
x-ms-clitelem:REDACTED
Set-Cookie:REDACTED
Date:Tue, 02 Nov 2021 06:07:20 GMT
Content-Type:application/json; charset=utf-8
Expires:-1
Content-Length:1353

DEBUG: ClientSecretCredential.GetToken succeeded. Scopes: [ https://graph.windows.net//.default ] ParentRequestId:  ExpiresOn: 2021-11-02T07:07:20.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: 'e8351e33-2fca-45d3-9859-97b6ad429db9', UserId: 'c9b6dd3e-34c5-403a-8097-b9e41571f040'
DEBUG: [Common.Authentication]: Authenticating using Account: 'c9b6dd3e-34c5-403a-8097-b9e41571f040', environment: 'AzureCloud', tenant: 'e8351e33-2fca-45d3-9859-97b6ad429db9'
DEBUG: 07:07:21 - [ServicePrincipalAuthenticator] Calling ClientSecretCredential.GetTokenAsync - ApplicationId:'c9b6dd3e-34c5-403a-8097-b9e41571f040', TenantId:'e8351e33-2fca-45d3-9859-97b6ad429db9', Scopes:'https://management.core.windows.net//.default', AuthorityHost:'https://login.microsoftonline.com/'
DEBUG: ClientSecretCredential.GetToken invoked. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId:
DEBUG: Request [0ad917e0-b004-4e84-bb61-9bcb0c523667] POST https://login.microsoftonline.com/e8351e33-2fca-45d3-9859-97b6ad429db9/oauth2/v2.0/token
x-client-SKU:REDACTED
x-client-Ver:REDACTED
x-client-CPU:REDACTED
x-client-OS:REDACTED
x-client-current-telemetry:REDACTED
x-client-last-telemetry:REDACTED
x-ms-lib-capability:REDACTED
client-request-id:REDACTED
return-client-request-id:REDACTED
x-app-name:REDACTED
x-app-ver:REDACTED
x-ms-client-request-id:0ad917e0-b004-4e84-bb61-9bcb0c523667
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.4.0,(.NET 5.0.11; Microsoft Windows 10.0.22000)
Content-Type:application/x-www-form-urlencoded
client assembly: Azure.Identity
DEBUG: Response [0ad917e0-b004-4e84-bb61-9bcb0c523667] 200 OK (00.1s)
Cache-Control:no-store, no-cache
Pragma:no-cache
Strict-Transport-Security:REDACTED
X-Content-Type-Options:REDACTED
P3P:REDACTED
client-request-id:REDACTED
x-ms-request-id:778b2bc0-da70-4970-8d63-3d5a56d94f00
x-ms-ests-server:REDACTED
x-ms-clitelem:REDACTED
Set-Cookie:REDACTED
Date:Tue, 02 Nov 2021 06:07:20 GMT
Content-Type:application/json; charset=utf-8
Expires:-1
Content-Length:1360

DEBUG: ClientSecretCredential.GetToken succeeded. Scopes: [ https://management.core.windows.net//.default ] ParentRequestId:  ExpiresOn: 2021-11-02T07:07:20.0000000+00:00
DEBUG: [Common.Authentication]: Received token with LoginType 'User', Tenant: 'e8351e33-2fca-45d3-9859-97b6ad429db9', UserId: 'c9b6dd3e-34c5-403a-8097-b9e41571f040'
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
POST

Absolute Uri:
https://graph.windows.net/e8351e33-2fca-45d3-9859-97b6ad429db9/getObjectsByObjectIds?api-version=1.6

Headers:
x-ms-client-request-id        : 418ef4cf-7041-4a98-afc4-ecd93dcaea40
Accept-Language               : en-US

Body:
{
  "objectIds": [
    "50d2e252-1c34-440f-9eee-54e827fa84ef"
  ],
  "includeDirectoryObjectReferences": true
}

DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
Forbidden

Headers:
Cache-Control                 : no-cache
Pragma                        : no-cache
ocp-aad-diagnostics-server-name: Y79ay6oZj3rVjKXcQ5q2woWFvfI4bZOWIxx0krqE9KQ=
request-id                    : de51a39b-6a90-43f7-8291-4c9976e06e68
client-request-id             : 418ef4cf-7041-4a98-afc4-ecd93dcaea40
x-ms-dirapi-data-contract-version: 1.6
ocp-aad-session-key           : mZIp2f8q5zDR1tJWSns8RmV_dNi41hwyWPY1sQ0rvW0Fy4M_SvZi0QiRHZBWx8KuzbKFCJsKVZARkUsHB7N_k3nS87m4hYJsxW6khTn1c7H_segVlLDUqRyAWPbujAWm.t0Z9J-JVmBPQlSuYlfxWvcuqpAM2_mmvU6TtXhiLpLU
Duration                      : 654775
x-ms-resource-unit            : 3
DataServiceVersion            : 3.0;
X-AspNet-Version              : 4.0.30319
X-Powered-By                  : ASP.NET
Strict-Transport-Security     : max-age=31536000; includeSubDomains
Access-Control-Allow-Origin   : *
Date                          : Tue, 02 Nov 2021 06:07:21 GMT

Body:
{
  "odata.error": {
    "code": "Authorization_RequestDenied",
    "message": {
      "lang": "en",
      "value": "Insufficient privileges to complete the operation."
    },
    "requestId": "de51a39b-6a90-43f7-8291-4c9976e06e68",
    "date": "2021-11-02T06:07:21"
  }
}

Error output

RequestId      : 
Message        : Exception of type 'Microsoft.Rest.Azure.CloudException' was thrown.
ServerMessage  : :  (System.Collections.Generic.List`1[Microsoft.Rest.Azure.CloudError])
ServerResponse : {Forbidden}
RequestMessage : {POST https://graph.windows.net/e8351e33-2fca-45d3-9859-97b6ad429db9/getObjectsByObjectIds?api-version=1.6}
InvocationInfo : {New-AzRoleAssignment}
Line           : New-AzRoleAssignment -ObjectId $groupObjectId -RoleDefinitionName Reader -ResourceGroupName $resourceGroupName -Debug
Position       : At line:1 char:1
                 + New-AzRoleAssignment -ObjectId $groupObjectId - …
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StackTrace     :    at Microsoft.Azure.Graph.RBAC.ObjectsOperations.GetObjectsByObjectIdsWithHttpMessagesAsync(GetObjectsParameters parameters, Dictionary`2 customHeaders, CancellationToken cancellationToken)
                    at Microsoft.Azure.Graph.RBAC.ObjectsOperationsExtensions.GetObjectsByObjectIdsAsync(IObjectsOperations operations, GetObjectsParameters parameters, CancellationToken cancellationToken)
                    at Microsoft.Azure.Graph.RBAC.ObjectsOperationsExtensions.GetObjectsByObjectIds(IObjectsOperations operations, GetObjectsParameters parameters)
                    at Microsoft.Azure.Commands.ActiveDirectory.ActiveDirectoryClient.GetObjectsByObjectId(List`1 objectIds)
                    at Microsoft.Azure.Commands.Resources.Models.Authorization.AuthorizationClient.CreateRoleAssignment(FilterRoleAssignmentsOptions parameters, Guid roleAssignmentId)
                    at Microsoft.Azure.Commands.Resources.NewAzureRoleAssignmentCommand.ExecuteCmdlet()
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
dingmeng-xue commented 2 years ago

Thanks for reporting. Your current service principal doesn't have sufficient permission. You need to grant permission to allow it access AAD Graph query directory object permission.

Agazoth commented 2 years ago

@dingmeng-xue yes, but that has been disabled in our tenant: Deprecated

dingmeng-xue commented 2 years ago

Microsoft Identity team had disabled AAD Graph on Portal. We provide a solution as workaround please reference https://github.com/Azure/azure-powershell/issues/16067

Agazoth commented 2 years ago

Thanks, @dingmeng-xue - any ETA on when the cmdlet is updated to support MSGraph?

I managed to solve the issue by using this REST API: https://docs.microsoft.com/en-us/rest/api/authorization/role-assignment-rest-sample

dingmeng-xue commented 2 years ago

My understanding is your solution can grant the rbac permission to your SP. For the time being, some management cmdlets calls AAD graph internally besides AAD cmdlets. for instance, New-AzAksCluster and Get-AzKeyVault, New-AzRoleAssignment. If you hope SP can use those cmdlets, required API permission is still needed.

We plan to support MSGraph at the beginning of the next month. The preview version of Az.Resources is published https://www.powershellgallery.com/packages/Az.Resources/5.0.0-preview. One announcement will be published soon.

Agazoth commented 2 years ago

That is good news. Thanks again.

The permission I needed for New-AzRoleAssignment to work was: Directory.Read.All

The workaround in #16067 gave my service account delegated access, but it also gave me a link to the deprecated portal menu, and I was able to grant application access from there: image