Get Graph API bearer token from Automation Runbook

Mickael PONSOT 6 Reputation points

Hi there,

I'm trying to build a powershell runbook in Azure automation which will make calls to Graph API and especially on intune.

To be able to do that I need of course to get a bearer token, but I tried several way to get it without any succes.

I tried by posting this request to :
$graphTokenRequestBody = @{
"scope" = "";
"grant_type" = "password";
"client_id" = "xxxx-xxxx-....";
"client_secret" = "yyyyyyyyyyy";
"username" = "myAcount";
"password" = "myPassword";

But I get "AADSTS50126: Error validating credentials due to invalid username or password." error which is apparently related to ADFS which we use in my company.

I also tried to call ADAL library in my script with this kind of call (and few variants) :

    *$platformParameters = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList "Auto"
    $userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList ($User, "OptionalDisplayableId")
    $AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $Credentials
    $authenticationResult = $authContext.AcquireTokenSilentAsync($resourceAppIdURI, $clientId, $userId, $platformParameters).GetAwaiter().Result;
    $token = $authenticationResult.AccessToken*

But then my authenticationResult is always empty.

And I also tried to use the Run as account (according to this this way :

$connection = Get-AutomationConnection -Name AzureRunAsConnection
$loginresults=Login-AzureRmAccount -ServicePrincipal -Tenant $connection.TenantID -ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint
$context = Get-AzureRmContext
$SubscriptionId = $context.Subscription
$cache = $context.TokenCache
$cacheItem = $cache.ReadItems()
$AccessToken=$cacheItem[$cacheItem.Count -1].AccessToken
$headerParams = @{'Authorization'="Bearer $AccessToken"}
$results=Invoke-RestMethod -Uri $url -Headers $headerParams -Method Get
Write-Output $results.value

But in this case it tells me that there is no TokenCache property in my context.

And finally I also tried with a custom PS module from this blog but It either fail in finding AzureAD mode or when I tweak it I still get an empty response.

So now I'm out of ideas.

Do anyone now how could I get this bearer token from my runbook ?

Thanks by advance

Azure Automation
Azure Automation
An Azure service that is used to automate, configure, and install updates across hybrid environments.
1,189 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,530 questions
0 comments No comments
{count} vote

2 answers

Sort by: Most helpful
  1. AmanpreetSingh-MSFT 56,501 Reputation points

    Hello @MickaelPONSOT-0221 Please find below the steps to allow Password (ROPC) flow without requiring the redirection to federated IDP for federated users.



    • Run Connect-AzureAD command and sign-in with Global Administrator account and run below cmdlet: New-AzureADPolicy -Definition @("{`"HomeRealmDiscoveryPolicy`":{`"AllowCloudPasswordValidation`":true,`"PreferredDomain`":`"`",`"AllowCloudPasswordValidation`":false}}") -DisplayName ROPC4ADFS -Type HomeRealmDiscoveryPolicy
    • Run Get-AzureADPolicy and copy the policy id of the ROPC4ADFS policy, created in the above step.
    • Run Get-AzureADServicePrincipal -SearchString < display_name_of_the_app > and copy the object ID of the service principal from the output.
    • Run Add-AzureADServicePrincipalPolicy -Id < objectID_of_the_service_principal > -RefObjectId < objectId_of_the_policy >

    This will allow federated user to authenticate directly from AzureAD without requiring to redirect to the federated Identity Provider (IDP) for the specific application.

    Please do not forget to "Accept the answer" wherever the information provided helps you. This will help others in the community as well.

    1 person found this answer helpful.

  2. sadomovalex 3,631 Reputation points

    hello, in order to enable username/password credentials authentication flow with AAD app (those app which client id and secret/certificate is used in your examples) this app should have allowPublicClient property set to true. Note that there are several pitfalls with it - they can be checked here Several problems when use Set-AzureADApplication cmdlet with AzureAD app with allowPublicClient = true .

    0 comments No comments