Functions/Get-GSuiteAccessToken.ps1
<#
.SYNOPSIS This function uses a permanent refresh token to get a temporary GSuite access token. #> function Get-GSuiteAccessToken { [CmdletBinding(PositionalBinding=$false)] [OutputType([String])] param ( # The application ID of the Google web application. [Parameter(Mandatory=$true, ParameterSetName="values")] [ValidateNotNullOrEmpty()] [String]$applicationId, # The client secret of the Google web application. [Parameter(Mandatory=$true, ParameterSetName="values")] [ValidateNotNullOrEmpty()] [String]$clientSecret, # The MSPComplete endpoint containing the application ID and client secret in the credential. [Parameter(Mandatory=$true, ParameterSetName="endpoint", ValueFromPipeline=$true)] [ValidateNotNull()] $endpoint, # The refresh token. [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$refreshToken, # Select the stream where the messages will be directed. [Parameter(Mandatory=$false)] [ValidateSet("Information", "Warning", "Error", "None")] [String]$outputStream = "Error" ) # Retrieve the properties from the endpoint if ($PSCmdlet.ParameterSetName -eq "endpoint") { $applicationId = $endpoint.Credential.Username $clientSecret = $endpoint.Credential.GetNetworkCredential().Password } # Construct the REST call $invokeRestMethodParams = @{ Uri = "https://www.googleapis.com/oauth2/v4/token" Method = "POST" Headers = @{ "Content-Type" = "application/json" } Body = @{ client_id = $applicationId client_secret = $clientSecret grant_type = "refresh_token" refresh_token = $refreshToken } | ConvertTo-Json } # Invoke the REST call Write-Information "Retrieving the GSuite access token using the refresh token" try { $response = Invoke-RestMethod @invokeRestMethodParams } catch { Write-OutputMessage "Exception occurred while retrieving the GSuite access token.`r`n$($_.Exception.Message)" -OutputStream $outputStream -ReturnMessage:$false return $null } # Verify the response if ($null -eq $response -or $response.expires_in -le 0 -or [String]::IsNullOrWhiteSpace($response.access_token)) { Write-OutputMessage "Failed to retrieve the GSuite access token." -OutputStream $outputStream -ReturnMessage:$false return $null } # Return the access token return $response.access_token } |