Automating MS Graph login

Highlighted
Visitor

Hello all, I've been trying for several days to successfully automate the pulling of a Intune inventory report of devices from MS graph. I can successfully use my personal credentials and a powershell script and retrieve this data, but where I'm running into trouble is the configuration of a service account to pull this report automatically on a schedule. I've been going back and forth over all the documentation and can't say that I've got a clear idea what the exact method should be to do this. I found how to at least pass user name and password to Graph without going through the web dialog, but the issue with that is that there seems to be no simple way to assign the proper graph permissions to an account without logging directly into an app that requests those permissions; my powershell script doesn't provide a web form to do admin consent obviously. So, i then found that you can create an "app" directly in the Azure portal, assign the rights and then grant permission and create an auth token using the app ID and client secret. the issue there is, when I use this, i get the error:

 

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

 

Any ideas what I'm missing? here's the code:

$client_id = [System.Web.HttpUtility]::UrlEncode("d3f28826-ea*********************************");
$client_secret = [System.Web.HttpUtility]::UrlEncode("ntISRPli7CR**********************************************")
$tenant_id = [System.Web.HttpUtility]::UrlEncode("a8362*************************************");
$resource = [System.Web.HttpUtility]::UrlEncode("https://graph.microsoft.com");
$scope= [System.Web.HttpUtility]::UrlEncode("https://graph.microsoft.com/.default");

$authority = "https://login.microsoftonline.com/$tenant_id";
$tokenEndpointUri = "$authority/oauth2/token";
$content = "grant_type=client_credentials&client_id=$client_id&client_secret=$client_secret&resource=$resource&scope=$scope";

$response = Invoke-WebRequest -Uri $tokenEndpointUri -Body $content -Method Post -UseBasicParsing
$responseBody = $response.Content | ConvertFrom-JSON
$access_token = $responseBody.access_token

 

$uri = "https://graph.microsoft.com/beta/managedDevices"
$Devices = (Invoke-RestMethod -Uri $uri –Headers @{"Authorization" = "Bearer $access_token"} –Method Get)

 

 

 

0 Replies