'CompactToken parsing failed with error code: -2147184105' when trying to access Users with Office 365 Unified API using PowerShell

Stefan picture Stefan · Feb 12, 2016 · Viewed 8.7k times · Source

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!

Answer

Marek Rycharski picture Marek Rycharski · Feb 18, 2016

The response actually indicates that the access token was not successfully generated or passed to the graph endpoint. Microsoft Graph couldn't parse it as a JWT token and thus attempted to process it as a Microsoft Account/Live Id compact token, which also failed. Please check the response that you got from the call to login.microsoftonline.com and that the token passed to graph.microsoft.com is a valid JWT token.