I am trying to list users using Office 365 Unified API with the following code:
$TenantID = "xxx"
$F_ClientID = "yyy"
$F_ClientSecret = "zzz"
Add-Type @'
using System;
public class OAuthContext{
public string AccessToken{get;set;}
public string TokenType{get;set;}
public string ExpiresIn{get;set;}
public string RefreshToken{get;set;}
}
'@
$Uri = "https://login.microsoftonline.com/$($TenantID)/oauth2/token"
$ContentType = 'application/x-www-form-urlencoded'
$Headers = @{}
$Body = [System.Text.Encoding]::UTF8.GetBytes('grant_type=client_credentials&client_id='+$F_ClientID+'&client_secret='+$F_Clie ntSecret+'&resource"=https://graph.microsoft.com')
$Response = Invoke-RestMethod -Method POST -Uri $Uri -Headers $Headers -ContentType $ContentType -Body $Body
$Response
$Context = New-Object OAuthContext
$Context.AccessToken = $Response.access_token
$Context.ExpiresIn = $Response.expires_in
$Context.RefreshToken = $Response.refresh_token
$Context.TokenType = $Response.token_type
$Context
$Headers = @{}
$Headers.Add('Authorization',$Context.TokenType + ' ' + $Context.AccessToken)
$Headers
$Uri = "https://graph.microsoft.com/v1.0/users"
Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
As seen from the result, the access token seems to be successfully generated. But when trying to list the users, I get the following error:
Invoke-RestMethod : {
"error": {
"code": "InvalidAuthenticationToken",
"message": "CompactToken parsing failed with error code: -2147184105",
"innerError": {
"request-id": "067c7044-0c59-4a39-86ac-b89e6b13229c",
"date": "2016-02-12T17:09:56"
}
}
}
At line:41 char:1
+ Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I don't really know what I am doing wrong here! Thanks for your help!
What i recommend is to test your query you are sending to the graph api by using the graph explorer tool first. and then mimic the same request in your PS script.
https://graphexplorer2.azurewebsites.net