简体   繁体   中英

Create azure application through Az module and assign API permissions using powershell

I have written a script which creates azure application using Az module, creates secret key, assigns owner. But assigning API permission gives insufficient permission error . The user is an admin user. Still unable to assign API permission. What wrong am I doing?

$ErrorActionPreference = 'Stop'
Connect-AzAccount
Import-Module Az.Resources
$tenant = Get-AzTenant
Set-AzContext -TenantId $tenant.Id
$AppName = Read-Host -Prompt 'Enter Application name '
$myApp = New-AzADApplication -DisplayName $AppName -IdentifierUris "http://$AppName.com"
Write-Host "App registered.."
$sp = New-AzADServicePrincipal -ApplicationId $myApp.ApplicationId -Role Owner
Write-Host "Service principal registered.."
$startDate = Get-Date
$endDate = $startDate.AddYears(100)
$secret = Read-Host -Prompt 'Enter App Secret Key ' -AsSecureString
$secPassword = ConvertTo-SecureString -AsPlainText -Force -String $secret
New-AzADAppCredential -ObjectId $myApp.ObjectId  -StartDate $startDate -EndDate $endDate -Password $secPassword

$ResourceAppIdURI = "https://graph.windows.net/"
# $authority = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token"
$authority = "https://login.windows.net/$tenant/oauth2/token"
$ClientCred = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $myApp.ApplicationId, $secret
$AuthContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority,$false
$AuthContext.TokenCache.Clear()
Start-Sleep -Seconds 10
$Token = $Authcontext.AcquireTokenAsync($ResourceAppIdURI, $ClientCred)

$AuthHeader = @{"Authorization" = $Token.Result.CreateAuthorizationHeader();"Content-Type"="application/json"}
$url = "https://graph.windows.net/$tenant/applications/$($myApp.ObjectID)?api-version=1.6"
Write-Host "URL: " $url

$postData = "{`"requiredResourceAccess`":[{`"resourceAppId`":`"00000003-0000-0000-c000-000000000000`",
`"resourceAccess`":[{`"id`":`"e1fe6dd8-ba31-4d61-89e7-88639da4683d`",`"type`":`"Scope`"}]}]}";
$result = Invoke-RestMethod -Uri $url -Method "PATCH" -Headers $AuthHeader -Body $postData
Write-Host "Result of App API permission: " $result

If you want to call Azure AAD graph API to assign permissions with OAuth 2.0 client credentials flow, we need to provide enough permissions(Azure AD Graph -> Aapplication permissions -> Application.ReadWrite.All )

在此处输入图像描述

Besides, regarding how to assign permissions to AD application with PowerShell, we also can use PowerShell module AzureAD .

For example

Connect-AzureAD
$AppAccess = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]@{
    ResourceAppId = "00000003-0000-0000-c000-000000000000";
    ResourceAccess =
        [Microsoft.Open.AzureAD.Model.ResourceAccess]@{
            Id = "";
            Type = ""},
        [Microsoft.Open.AzureAD.Model.ResourceAccess]@{
            Id = "";
            Type = ""}
}
Set-AzureADApplication -ObjectId <the app object id> -RequiredResourceAccess $AppAccess 

Update

According to my test, when we use Az module, we can use the following method to get access token and call AAD graph rest API. But please note that when you use the method, the account you use to run Connect-AzAccount should be Azure AD Global Admin

Connect-AzAccount

$context =Get-AzContext
$dexResourceUrl='https://graph.windows.net/'
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, 
                                $context.Environment, 
                                $context.Tenant.Id.ToString(),
                                 $null, 
                                 [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, 
                                 $null, $dexResourceUrl).AccessToken

# assign permissions
$headers =@{}
$headers.Add("Content-Type", "application/json")
$headers.Add("Accept", "application/json")
$headers.Add("Authorization", "Bearer $($token)")
$body = "{
`n    `"requiredResourceAccess`": [{
`n            `"resourceAppId`": `"00000003-0000-0000-c000-000000000000`",
`n            `"resourceAccess`": [
`n              {
`n                  `"id`": `"405a51b5-8d8d-430b-9842-8be4b0e9f324`",
`n                  `"type`": `"Role`"
`n              },
`n              {
`n                  `"id`": `"09850681-111b-4a89-9bed-3f2cae46d706`",
`n                  `"type`": `"Role`"
`n              }
`n          ]
`n        }
`n    ]
`n}
`n"
$url ='https://graph.windows.net/hanxia.onmicrosoft.com/applications/d4975420-841f-47d5-a3d2-0870901f13cd?api-version=1.6'
Invoke-RestMethod $url  -Method 'PATCH' -Headers $headers -Body $body

#check if adding the permissions you need
$headers =@{}
$headers.Add("Accept", "application/json")
$headers.Add("Authorization", "Bearer $($token)")
$url ='https://graph.windows.net/hanxia.onmicrosoft.com/applications/<aad application object id>?api-version=1.6'
$response=Invoke-RestMethod $url  -Method 'GET' -Headers $headers 
$response.requiredResourceAccess | ConvertTo-Json

在此处输入图像描述

In my case, the easiest way to do this without messing around with http requests, was to combine the Azure-powershell module and the Az cli module

So, once I have created my new app:

$myApp = New-AzADApplication -DisplayName $AppName -IdentifierUris "http://$AppName.com"

Then I would login into azure using the Az Cli , and, for instance:

  • Add some api permissions
  • Grant these permissions directory admin consent ( if needed )
. { $azcliLogin = az login }
. { az account set --subscription $config.subscriptionId }
. { az ad app permission add --id $myApp.appid --api 00000002-0000-0000-c000-000000000000 --api-permissions 78c8a3c8-a07e-4b9e-af1b-b5ccab50a175=Role }
. { $appApiGrant = az ad app permission grant --id $config.azureAccess.appid --api 00000002-0000-0000-c000-000000000000 }
. { az ad app permission admin-consent --id $myApp.appid }

Where:

--api 00000002-0000-0000-c000-000000000000 Refers to Microsoft Graph API

--api-permissions 78c8a3c8-a07e-4b9e-af1b-b5ccab50a175=Role Refers to some role on this api, as Directory.ReadWrite.All

You can get the required API and API-PERMISSIONS guids from the App manifiest in Azure在此处输入图像描述

This way you create the app with the required granted api permissions, in a single powershell script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM