Skip to content

Instantly share code, notes, and snippets.

@moiaune
Last active December 18, 2019 12:29
Show Gist options
  • Save moiaune/0aeb4e0b7495df5cda31509d8a1cbfcb to your computer and use it in GitHub Desktop.
Save moiaune/0aeb4e0b7495df5cda31509d8a1cbfcb to your computer and use it in GitHub Desktop.
Basic Microsoft Graph Authentication in Powershell
[CmdletBinding()]
param (
[Parameter(Mandatory=$True)]
[string]
$TenantName,
[Parameter(Mandatory=$True)]
[string]
$AppId,
[Parameter(Mandatory=$True)]
[string]
$AppSecret
)
begin {
$Scope = 'https://graph.microsoft.com/.default'
$TokenUrl = "https://login.microsoftonline.com/$($TenantName)/oauth2/v2.0/token"
$Body = @{
client_id = $AppId
client_secret = $AppSecret
scope = $Scope
grant_type = 'client_credentials'
}
$PostSplat = @{
ContentType = 'application/x-www-form-urlencoded'
Method = 'POST'
Body = $Body
Uri = $TokenUrl
}
try {
$Request = Invoke-RestMethod @PostSplat
}
catch {
throw $_
}
$Headers = @{
Authorization = "{0} {1}" -f ($Request.token_type, $Request.access_token)
}
}
process {
$Me = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/me" -Method GET -Headers $Headers
$Me
}
end {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment