azurepowershellmicrosoft-graph-apimicrosoft-graph-sdks

How can I log the request headers of Invoke-MgRestMethod to inspect the Microsoft.Graph access token?


For debugging purposes, I want to inspect the access token obtained by calling Connect-MgGraph. As I don't see any direct support for this, I have tried to use Invoke-MgRestMethod to inspect to request headers (Authorization).

However, the following call doesn't display the headers:

Invoke-GraphRequest -Method Get -Uri /v1.0/me -Verbose 

How can I get hold of the access token?

https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.authentication/invoke-mggraphrequest?view=graph-powershell-1.0


Solution

  • The cmdlet Invoke-GraphRequest has parameter OutputType. If you set OutputType to HttpResponseMessage, you should be able to access request headers, including Authorization header.

    $mgRequest = Invoke-GraphRequest -Method Get -Uri /v1.0/me -OutputType HttpResponseMessage
    
    $mgRequest.RequestMessage.Headers.Authorization.Parameter
    

    If you also need to access data:

    $responseBody = $mgRequest.Content.ReadAsStringAsync().Result
    $responseBody