Skip to content

Instantly share code, notes, and snippets.

@LindaLawton
Last active December 6, 2021 05:18
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LindaLawton/55115de5e8b366be3969b24884f30a39 to your computer and use it in GitHub Desktop.
Save LindaLawton/55115de5e8b366be3969b24884f30a39 to your computer and use it in GitHub Desktop.
Step by step guild to using power shell to get a Google access token.
clear-host;
#Remove-Variable * -ErrorAction SilentlyContinue
#get-item Variable:*
#Get-Variable | Select-Object -ExpandProperty Name
. C:\Users\linda_l\Desktop\PowerShell\GoogleOauth.ps1
Add-Type -Path "C:\Users\linda_l\Documents\visual studio 2015\Projects\TestingLibrary\packages\AE.Net.Mail.1.7.10.0\lib\net45\AE.Net.Mail.dll"
Add-Type -AssemblyName System.IO
Add-Type -AssemblyName System.Text.Encoding
$clientId = "46123799103-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com";
$secret = "pj6hx1H2N5BFqdnaNhIbie";
#$AuthURL = GetAuthURL $clientId "https://mail.google.com/"
#Write-Host "Google Auth URL: " $AuthURL;
#$code = "4/IUVt9ULs5ZBX_Hd4pLQ2LyuE8xgNWjiCfCUKA1BZMGQ";
#ExchangeCode $clientId $secret $code
$refreshToken = "1/Wo0UO4_dYY2z6BJ3idi9WaHR838FJ19XU0-p7j1Rtzs";
$accessToken = RefreshAccessToken $clientId $secret $refreshToken
function Base64UrlEncode([string]$msgStr2)
{
$inputBytes = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($msgStr2));
# Special "url-safe" base64 encode.
$inputBytes = $inputBytes.Replace('+', '-').Replace('/', '_').Replace("=", "");
return $inputBytes;
}
$email = new-object MailAddress("test@test.com");
$msg2 = new-object AE.Net.Mail.MailMessage;
$msg2.To.Add($email);
$msg2.Subject = "Your Subject";
$msg2.Body = "Hello , world from Gmail API!";
$msg2.From = $email;
$msgStr = new-object System.IO.StringWriter;
$msg2.Save($msgStr);
$encodedEmail = Base64UrlEncode $msgStr;
#Write-Host $encodedEmail;
# Setup:
#
# Step 1: create new project on https://console.developers.google.com.
# Step 2: Create oauth credentials type native or other.
# Save the client id and secret.
# Step 3: Enable the api you are intersted in accessing.
# Look up what scopes you need for accssing this api,
# Step 4: Using the client id, and client secret from the
#
#
# Inital Authenticate: Authentication must be done the first time via a webpage create the link you will need. More then one scope can be added simply by seporating them with a comama
# Place it in a webbrowser.
#
# https://accounts.google.com/o/oauth2/auth?client_id={CLIENT ID}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope={SCOPES}&response_type=code
#
# Copy the authencation code and run the following script.
# note: AuthorizationCode can only be used once you will need to save the refresh token returned to you.
$clientId = "{CLIENT ID}";
$secret = "{SECRET}";
$redirectURI = "urn:ietf:wg:oauth:2.0:oob";
$AuthorizationCode = '{Code from web browser link above}';
$tokenParams = @{
client_id=$clientId;
client_secret=$secret;
code=$AuthorizationCode;
grant_type='authorization_code';
redirect_uri=$redirectURI
}
$token = Invoke-WebRequest -Uri "https://accounts.google.com/o/oauth2/token" -Method POST -Body $tokenParams | ConvertFrom-Json
# Save this
$token.refresh_token
##########################################################################################################################
#
# Using refresh token to get new access token
# The access token is used to access an api by sending the access_token parm with any request.
# Access tokens are only valid for about an hour after that you will need to request a new one using your refresh_token
#
##########################################################################################################################
$clientId = "{CLIENT ID}";
$secret = "{SECRET}";
$redirectURI = "urn:ietf:wg:oauth:2.0:oob";
$refreshToken = "{Refresh token from the authentcation flow}";
$refreshTokenParams = @{
client_id=$clientId;
client_secret=$secret;
refresh_token=$refreshToken;
grant_type='refresh_token';
}
$refreshedToken = Invoke-WebRequest -Uri "https://accounts.google.com/o/oauth2/token" -Method POST -Body $refreshTokenParams | ConvertFrom-Json
$accesstoken = $refreshedToken.access_token
# This will work assuming you used the gmail scope I was just testing this
$messages = Invoke-WebRequest -Uri "https://www.googleapis.com/gmail/v1/users/me/messages?access_token=$accesstoken"-Method Get | ConvertFrom-Json
# Apperntly powershell 2.0 doesnt have Invoke-WebRequest we can also use Invoke-RestMethod
#
Invoke-RestMethod -Uri "https://www.googleapis.com/gmail/v1/users/me/messages?access_token=$accesstoken" | select-object -expandproperty messages | format-table
function GetAuthURL([string]$clientId ,[string]$scopes) {
$hold = "https://accounts.google.com/o/oauth2/auth?client_id=$clientId&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=$scopes&response_type=code";
return $hold;
}
function ExchangeCode([string]$clientId,[string]$secret, [string]$code){
$data = “code=$code&client_id=$clientId&client_secret=$secret&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code”;
try {
$response = Invoke-RestMethod -Uri "https://accounts.google.com/o/oauth2/token" -Method Post -Body $data
} catch {
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}
#4/regHkmE9-e8xrLsgnmSOqbsq3T-xrTAxyXelv21hoSs
}
function RefreshAccessToken([string]$clientId,[string]$secret, [string]$refreshToken){
$data = "client_id=$clientId&client_secret=$secret&refresh_token=$refreshToken&grant_type=refresh_token"
try {
$response = Invoke-RestMethod -Uri https://www.googleapis.com/oauth2/v4/token -Method POST -Body $data
return $response.access_token;
} catch {
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}
}
@thuhuyentn
Copy link

Hello Linda,

Thank you for this post! I'm new to Google Authentication, Powershell and C# so coming across your post is the most awesome findings in months for me.

I'd love to have your help sheding some light on my situation here:

The Google Ads account is set up by someone else. I gave the person the Authentication link, and then the authentication code is run by that same person and passed back to me.

I was able to run the first section and got Refresh Token back. However, get new access token failed with the following message. "Invoke-WebRequest : The remote server returned an error: (403) Forbidden."

Where does I start to resolve this?

Thu Huyen

Thu

@LindaLawton
Copy link
Author

LindaLawton commented Apr 7, 2017

None of this is stable its more a place for me to dump things while i am still working on them. This is work in progress i would like to have some powershell examples for a few of the Google APIs.

@DevenSuji
Copy link

Hi Linda,
Will you be able to post the full steps on how to access, post, get and delete in Google sheets with power shell please.

@LindaLawton
Copy link
Author

Sorry this is all i have I dont use windows anymore as a daily driver so havent used power shell in ages. It should be the same though just follow the auth example and then check the documentation for how to send the commands to sheet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment