Skip to content

Instantly share code, notes, and snippets.

@junecastillote
Last active December 29, 2019 07:12
Show Gist options
  • Save junecastillote/b9fc875303ec98487483f26b9680c462 to your computer and use it in GitHub Desktop.
Save junecastillote/b9fc875303ec98487483f26b9680c462 to your computer and use it in GitHub Desktop.
Function Get-MSGraphOAuthToken {
<#
.SYNOPSIS
Acquire authentication token for MS Graph API
.DESCRIPTION
If you have a registered app in Azure AD, this function can help you get the authentication token
from the MS Graph API endpoint. Each token is valid for 60 minutes.
.PARAMETER ClientID
This is the registered Application ID in AzureAD
.PARAMETER ClientSecret
This is the secret key of the registered app in AzureAD
.PARAMETER TenantID
This is your Office 365 Tenant ID/Domain
.EXAMPLE
$oauth = Get-MSGraphOAuthToken -ClientID $ClientID -ClientSecret $ClientSecret -TenantID $TenantID
The above example gets a new token using the ClientID, ClientSecret and TenantID combination
.NOTES
The access token is stored in the Header property of the returned object
#>
param (
[Parameter(Mandatory, Position = 0)]
[ValidateNotNullOrEmpty()]
[string]
$ClientID,
[Parameter(Mandatory, Position = 1)]
[ValidateNotNullOrEmpty()]
[string]
$ClientSecret,
[Parameter(Mandatory, Position = 2)]
[ValidateNotNullOrEmpty()]
[string]
$TenantID
)
# Build the POST Request Parameters
$request = @{
Method = 'POST'
URI = "https://login.microsoftonline.com/$TenantID/oauth2/v2.0/token"
body = @{
grant_type = "client_credentials"
scope = "https://graph.microsoft.com/.default"
client_id = $ClientID
client_secret = $ClientSecret
}
}
try {
# Request for OAuth
$oauth = Invoke-RestMethod @request -ErrorAction STOP
# Add the Header property to OAuth
$oauth | Add-Member -MemberType NoteProperty -Name Header -Value @{'Authorization' = "$($oauth.token_type) $($oauth.access_token)" }
# Add the OAuthStart property to OAuth - Token valid start time
$oauth | Add-Member -MemberType NoteProperty -Name Auth_Start -Value (Get-Date)
# Add the OAuthEnd property to OAuth - Token expiration time
$oauth | Add-Member -MemberType NoteProperty -Name Auth_End -Value (Get-Date).AddSeconds($oauth.expires_in)
# Return the $oauth object
return $oauth
}
catch {
Write-Output $_.Exception.Message
Break
}
}
<# EXAMPLE
$ClientID = 'client-id'
$ClientSecret = 'client-secret'
$TenantID = 'tenant-id'
$oauth = Get-MSGraphOAuthToken $ClientID $ClientSecret $TenantID
$oauth.Header
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment