Google Oauth fails with Powershell Invoke-RestMethod while works with Invoke-Webrequest

Viewed 245

while experimenting Google Oauth authentication, I have some issues when using Invoke-RestMethod in place of Invoke-WebRequest, which is working. See the samples below. What's wrong with Invoke-RestMethod? No wonder why Microsoft is using Invoke-WebRequest in the official documents... :-)

Invoke-WebRequest

$Global:Token_uri = "https://www.googleapis.com/oauth2/v4/token";
$scopes = "https://www.googleapis.com/auth/photoslibrary https://www.googleapis.com/auth/photoslibrary.readonly https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata https://www.googleapis.com/auth/photoslibrary.appendonly https://www.googleapis.com/auth/photoslibrary.sharing";
$redirect_uri = "urn:ietf:wg:oauth:2.0:oob";
$grant = "authorization_code";
# Launch browser to start initial authentication
Start-Process "https://accounts.google.com/o/oauth2/v2/auth?client_id=$Global:ClientId&scope=$([string]::Join("%20", $scopes))&access_type=offline&response_type=code&redirect_uri=$redirect_uri";
$code = Read-Host "Please enter Google authentication code"   
$body = "client_id=$Global:ClientId&client_secret=$Global:CSecret&redirect_uri=$redirect_uri&code=$code&grant_type=authorization_code"   
    
# This works
$response = Invoke-WebRequest https://www.googleapis.com/oauth2/v4/token -ContentType application/x-www-form-urlencoded -Method POST -Body $body

Invoke-RestMethod

$Global:Token_uri = "https://www.googleapis.com/oauth2/v4/token";
$scopes = "https://www.googleapis.com/auth/photoslibrary https://www.googleapis.com/auth/photoslibrary.readonly https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata https://www.googleapis.com/auth/photoslibrary.appendonly https://www.googleapis.com/auth/photoslibrary.sharing";
$redirect_uri = "urn:ietf:wg:oauth:2.0:oob";
$grant = "authorization_code";    
# Launch browser to start initial authentication
Start-Process "https://accounts.google.com/o/oauth2/v2/auth?client_id=$Global:ClientId&scope=$([string]::Join("%20", $scopes))&access_type=offline&response_type=code&redirect_uri=$redirect_uri";
$code = Read-Host "Please enter Google authentication code"

$body = @{
    code = $code;
    client_id = $Global:ClientId;
    client_secret = $Global:CSecret;
    redirect_uri = $redirect_uri;
    grant_type = $grant;
};

# throws 400
$response  = Invoke-RestMethod -Uri $Global:Token_uri -Method POST -Body $body -ContentType "application/x-www-form-urlencoded";
0 Answers
Related