FunctionsPublic/Get-GraphAccessToken.ps1
<#
.SYNOPSIS Get AAD Access Token .DESCRIPTION Function uses a Client ID and Client Secret to authenticate against a specific AAD tenant and obtains an access token. #> function Get-GraphAccessToken { [cmdletbinding()] param ( [string]$tenantID, [string]$clientID, [string]$clientSecret ) process { if($tenantID.Length -eq 0 -or $clientID.Length -eq 0 -or $clientSecret.Length -eq 0) { Write-Error "Invalid input received. Please specify all parameters in order to use this function." return $null } $tokenAuthURI = "https://login.microsoftonline.com/$($tenantID)/oauth2/v2.0/token" Write-Debug "Using '$($tokenAuthURI)' 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=https://graph.microsoft.com/.default" $RequestedDate = Get-Date Write-Debug "Passing $($requestBody) to authentication endpoint." # # POST the request body to the token URI # $tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenAuthURI -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() } } } |