question

MickaelPONSOT-0221 avatar image
1 Vote"
MickaelPONSOT-0221 asked sadomovalex published

Get Graph API bearer token from Automation Runbook

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 https://login.microsoftonline.com/sartorius.com/oauth2/v2.0/token :
$graphTokenRequestBody = @{
"scope" = "https://graph.microsoft.com/.default";
"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 https://medium.com/@createdincode/making-azure-management-api-calls-with-azure-automation-runbooks-745c5ba541ee) 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
$resourceGroup="MyResourceGroup"
$headerParams = @{'Authorization'="Bearer $AccessToken"}
$url="https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Compute/virtualMachines?api-version=2018-06-01"
$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 https://msendpointmgr.com/2018/02/26/getting-started-with-microsoft-intune-and-azure-automation/ 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-automationazure-ad-graph
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

amanpreetsingh-msft avatar image
1 Vote"
amanpreetsingh-msft answered JamesTran-MSFT commented

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


Pre-requisites:


Make sure you have Password Hash Sync (PHS) enabled for your tenant


Latest version of AzureAD PowerShell Module (2.0.2.105).


Steps:


Run Connect-AzureAD command and sign-in with Global Administrator account and run below cmdlet:

New-AzureADPolicy -Definition @("{`"HomeRealmDiscoveryPolicy`":{`"AllowCloudPasswordValidation`":true,`"PreferredDomain`":`"example.com`",`"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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@MickaelPONSOT-0221
I just wanted to check in and see if you required additional assistance or if you were able to resolve this issue?


If any reply/answer helped resolve your question, please remember to "mark as answer" so that others in the community facing similar issues can easily find the solution.

0 Votes 0 ·
sadomovalex avatar image
0 Votes"
sadomovalex answered sadomovalex published

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 .


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.