Undeprecate my Powershell

So I was attempting to…

Login

Blog History

So I was attempting to create a Powershell script that would Create an Azure AD Application and do the Application Admin consent aswell

The script I had as a sample used AzureRM to get a refresh token and then get an access token to then do the POST to the https://main.iam.ad.ext.azure.com/api/ endpoint as follows:

Function Grant-OAuth2PermissionsToApp {
   Login-AzureRMAccount
   $azureAdContext = Get-AzureRmContext
   $refreshToken = @($azureAdContext.TokenCache.ReadItems() | Where { $_.tenantId -eq $tenantId -and $_.ExpiresOn -gt (Get-Date) })[0].RefreshToken
   $body = "grant_type=refresh_token&refresh_token=$($refreshToken)&resource=74658136-14ec-4630-ad9b-26e160ff0fc6"
   $apiToken = Invoke-RestMethod "https://login.windows.net/$tenantId/oauth2/token" -Method POST -Body $body -ContentType 'application/x-www-form-urlencoded'
   $header = @{
      'Authorization'          = 'Bearer ' + $apiToken.access_token
      'X-Requested-With'       = 'XMLHttpRequest'
      'x-ms-client-request-id' = [guid]::NewGuid()
      'x-ms-correlation-id'    = [guid]::NewGuid()
   }
   $url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$newAppId/Consent?onBehalfOfAll=true"
   Invoke-RestMethod -Uri $url -Headers $header -Method POST -ErrorAction Stop
}

But I wanted to remove the dependency to the older and deprecated AzureRM module. I tried to use Enable-AzureRMAlias but then $azureAdContext.TokenCache.ReadItems() didn't exist

So then it was down to Google for a few hours and this is what I came up with that worked using the newer Az module... The following seems to work

Function Grant-OAuth2PermissionsToApp {
    Login-AzAccount
    $context = Get-AzContext
 
    if ($null -eq $context) {
        $null = Connect-AZAccount -EA stop
        $context = Get-AzContext
    }
    
    #  get an access token to access resource https://main.iam.ad.ext.azure.com / 74658136-14ec-4630-ad9b-26e160ff0fc6
    $token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id, $null, "Never", $null, "74658136-14ec-4630-ad9b-26e160ff0fc6")
 
    $header = @{
        'Authorization'          = 'Bearer ' + $token.AccessToken
        'X-Requested-With'       = 'XMLHttpRequest'
        'x-ms-client-request-id' = [guid]::NewGuid()
        'x-ms-correlation-id'    = [guid]::NewGuid()
    }
     
    $url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$newAppId/Consent?onBehalfOfAll=true"
 
    Invoke-RestMethod -Uri $url -Headers $header -Method POST -ErrorAction Stop
}
 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.