Skip to content

Instantly share code, notes, and snippets.

@aflyen
Created March 18, 2020 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aflyen/ba9450dae698c5167919f23684925e3a to your computer and use it in GitHub Desktop.
Save aflyen/ba9450dae698c5167919f23684925e3a to your computer and use it in GitHub Desktop.
# Connects to Azure Active Directory to authenticate and retrieve a valid access token using a Client ID and secret
function Get-CorpMicrosoftGraphAccessToken
{
param(
[string] $TenantId,
[string] $ClientId,
[string] $ClientSecret
)
$AccessToken = ""
$Method = "POST"
$ContentType = "application/x-www-form-urlencoded"
$Uri = "https://login.microsoftonline.com/$($TenantId)/oauth2/v2.0/token"
$Body = "client_id=$($ClientId)&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=$($ClientSecret)&grant_type=client_credentials"
try
{
$Response = Invoke-WebRequest -Uri $Uri -Method $Method -ContentType $ContentType -Body $Body -UseBasicParsing
$Content = ConvertFrom-Json $Response.Content
$AccessToken = $Content.access_token
Write-Host "Access token aquired from Microsoft Graph"
}
catch
{
Write-Error "Unable to aquire access token from Microsoft Graph"
}
return $AccessToken
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment