azure-powershell icon indicating copy to clipboard operation
azure-powershell copied to clipboard

Executing Get-AzureRmRoleAssignment as Service Principal results in an exception

Open pascalnaber opened this issue 9 years ago • 4 comments

Cmdlet(s)

Get-AzureRmRoleAssignment (executed as Service Principal)

the following permissions are added to the service principall:

Windows Azure Active Directory 6 application permissions - 6 delegated permissions (not able to select them all, only where Requires Admin=Yes) Microsoft Graph - 20 application permissions - 20 delegated permissions (also not able to select them all)

PowerShell Version

Version 5.1.14393.693.

Module Version

The AzureRM version is 3.6

OS Version

Name Value


PSVersion 5.1.14393.693
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.14393.693
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

Description

When executing Get-AzureRmRoleAssignment as Service Principal (with AAD permissions and Graph permissions), an exception is raised.

Debug Output

Body: { "odata.error": { "code": "Authentication_Unauthorized", "message": { "lang": "en", "value": "Access denied to the specified API version." }, "requestId": "f895e245-f259-47fd-acff-70f0b2000b7a", "date": "2017-02-25T19:51:07" } }

Get-AzureRmRoleAssignment : Exception of type 'Microsoft.Rest.Azure.CloudException' was thrown. At line:1 char:1

  • Get-AzureRmRoleAssignment -debug
  •   + CategoryInfo          : CloseError: (:) [Get-AzureRmRoleAssignment], CloudException
      + FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.GetAzureRoleAssignmentCommand
    
    

DEBUG: 8:51:12 PM - GetAzureRoleAssignmentCommand end processing. DEBUG: 8:51:12 PM - GetAzureRoleAssignmentCommand end processing.

Script/Steps for Reproduction

  1. Create a Service Principal with:

     (
         [Parameter(Mandatory=$true, HelpMessage="Enter Azure Subscription name. You need to be Subscription Admin to execute the script")]
         [string] $subscriptionName,    
         [Parameter(Mandatory=$true, HelpMessage="Provide a password for SPN application that you would create")]
         [string] $password,    
     Mandatory=$false, HelpMessage="Provide a SPN role assignment")]
         [string] $spnRole = "owner"
     )
    
     #Initialize
     $ErrorActionPreference = "Stop"
     $VerbosePreference = "SilentlyContinue"
     $userName = $env:USERNAME
     $newguid = [guid]::NewGuid()
     $displayName = [String]::Format("SP.{0}.{1}", $resourceGroupName, $newguid)
     $homePage = "http://" + $displayName
     $identifierUri = $homePage
    
    
     #Initialize subscription
     $isAzureModulePresent = Get-Module -Name AzureRM* -ListAvailable
     if ([String]::IsNullOrEmpty($isAzureModulePresent) -eq $true)
     {
         Write-Output "Script requires AzureRM modules to be present. Obtain AzureRM from https://github.com/Azure/azure-powershell/releases. Please refer https://github.com/Microsoft/vsts-tasks/blob/master/Tasks/DeployAzureResourceGroup/README.md for recommended AzureRM versions." -Verbose
         return
     }
    
     Import-Module -Name AzureRM.Profile
     Write-Output "Provide your credentials to access Azure subscription $subscriptionName" -Verbose
     Login-AzureRmAccount -SubscriptionName $subscriptionName
     $azureSubscription = Get-AzureRmSubscription -SubscriptionName $subscriptionName
     $connectionName = $azureSubscription.SubscriptionName
     $tenantId = $azureSubscription.TenantId
     $id = $azureSubscription.SubscriptionId
    
    
     #Create a new AD Application
     Write-Output "Creating a new Application in AAD (App URI - $identifierUri)" -Verbose
     $azureAdApplication = New-AzureRmADApplication -DisplayName $displayName -HomePage $homePage -IdentifierUris $identifierUri -Password $password -Verbose
     $appId = $azureAdApplication.ApplicationId
     Write-Output "Azure AAD Application creation completed successfully (Application Id: $appId)" -Verbose
    
    
     #Create new SPN
     Write-Output "Creating a new SPN" -Verbose
     $spn = New-AzureRmADServicePrincipal -ApplicationId $appId
     $spnName = $spn.ServicePrincipalNames
     Write-Output "SPN creation completed successfully (SPN Name: $spnName)" -Verbose
    
     #Assign role to SPN
     Write-Output "Waiting for SPN creation to reflect in Directory before Role assignment"
     Start-Sleep 20
     Write-Output "Assigning role ($spnRole) to SPN App ($appId)" -Verbose
     New-AzureRmRoleAssignment -RoleDefinitionName $spnRole -ServicePrincipalName $appId 
     Write-Output "SPN role assignment completed successfully" -Verbose
    
    
     #Print the values
     Write-Output "`nCopy and Paste below values for Service Connection" -Verbose
     Write-Output "***************************************************************************"
     Write-Output "Connection Name: $connectionName(SPN)"
     Write-Output "Subscription Id: $id"
     Write-Output "Subscription Name: $connectionName"
     Write-Output "Service Principal Id: $appId"
     Write-Output "Service Principal key: <Password that you typed in>"
     Write-Output "Tenant Id: $tenantId"
     Write-Output "***************************************************************************"
    

2. Add permissions as stated above in the azure portal

3. Login with Service Principal

$psCredential = New-Object System.Management.Automation.PSCredential("98349834-8494-4813-9282-4343434", (ConvertTo-SecureString "myPassword" -AsPlainText -Force))
Add-AzureRMAccount -ServicePrincipal -Tenant "123456-d5bb-44f8-a283-34534434" -Credential $psCredential
4. Execute the powershell command that throws an exception:

`Get-AzureRmRoleAssignment -debug `

pascalnaber avatar Feb 25 '17 19:02 pascalnaber

Just to add more drama, querying the same information using the same principal with python code works:

from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.authorization import AuthorizationManagementClient tenant_id = 'tenant_guid' application_id = 'application_guid' application_secret = 'application_secret' cred = ServicePrincipalCredentials(client_id=application_id, secret=application_secret, tenant=tenant_id) client = AuthorizationManagementClient(cred, 'subscription_guid') roles = client.role_assignments.list() for role in roles: print(role)

4c74356b41 avatar Feb 25 '17 20:02 4c74356b41

The same exception comes up when using Remove-AzureRmRoleAssignment, executed as service principal.

Remove-AzureRmRoleAssignment -RoleDefinitionName "Contributor" -ServicePrincipalName "1234-8494-4813-9282-989898"

pascalnaber avatar Feb 26 '17 19:02 pascalnaber

@pascalnaber This is due to the whitelisting of the api-version used by the graph client in the cmdlet. Whitelisting means that only first party applications are allowed to use the api, so that the cmdlets work with user credentials, but not application credentials. This is a duplicate of this issue: #3407

This is due to be fixed as the new graph api service is pushed out in a few weeks. Cloaing as duplicate for now, please track in the duplicate bug

markcowl avatar Mar 11 '17 02:03 markcowl

Still the same error with the version 4.1.0 of the module AzureRM.Resources Any issue ?

YoannGUILLO avatar Jun 09 '17 13:06 YoannGUILLO