Last active
December 18, 2019 12:29
-
-
Save moiaune/0aeb4e0b7495df5cda31509d8a1cbfcb to your computer and use it in GitHub Desktop.
Basic Microsoft Graph Authentication in Powershell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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