FunctionsPublic/Get-ProxsysGraphAccessToken.ps1

<#
.SYNOPSIS
Get Proxsys Graph Access Token
 
.DESCRIPTION
Function uses a Client ID and Client Secret to authenticate against the Proxsys Graph and obtains an access token.
#>

function Get-ProxsysGraphAccessToken
{
    [cmdletbinding()]
    param ( 
        [string]$clientID, 
        [string]$clientSecret,
        [PSobject]$authenticationInfo
    )

    process
    {
        if($clientID.Length -eq 0 -or
            $clientSecret.Length -eq 0 -or
            $null -eq $authenticationInfo)
        {
            Write-Error "Invalid input received. Please specify all parameters in order to use this function."
            return $null
        }

        Write-Debug "Using '$($authenticationInfo.TokenEndpoint)' as token authentication endpoint."
        #
        # Construct the request body
        #
        $requestBody = "grant_type=client_credentials" + 
            "&client_id=$($clientID)" +
            "&client_secret="+ ([System.Web.HttpUtility]::UrlEncode($clientSecret)) +
            "&redirect_uri=https%3A%2F%2Fcdi.proxsys.net" + 
            "&scope=cdi" + 
            "&code=authorization_code"

        $RequestedDate = Get-Date

        Write-Debug "Passing $($requestBody) to authentication endpoint."
        #
        # POST the request body to the token URI
        #
        $tokenResponse = Invoke-RestMethod -Method POST -Uri $authenticationInfo.TokenEndpoint -body $requestBody -ContentType "application/x-www-form-urlencoded"

        Write-Debug "Response retrieved from token endpoint with $($tokenResponse.Length) bytes length."
        
        #
        # Get token from the tokenResponse
        #
        $SecureAccessToken = $tokenResponse.access_token | ConvertTo-SecureString -AsPlainText -Force
        $AccessTokenCredential = [pscredential]::new('access_token', $SecureAccessToken )

        #
        # Construct 'AccessToken' object
        #
        @{
            Application = $Application
            AccessTokenCredential = $AccessTokenCredential
            RequestedDate = $RequestedDate
            Response = $tokenResponse | Select-Object -property * -ExcludeProperty access_token, refresh_token
            LastRequestDate = $RequestedDate
            Session = $Session
            GUID = [guid]::NewGuid()
        }
    }
}