DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

Get AAD AccessToken via PowerShell with user password

I needed to get Azure AD Access Token by using hard-coded username and password. To do so, we can use grant_type=password.

Prerequisites

I registered an application to Azure AD to user for this.

PowerShell script

I used following PowerShell script to get access token. As I didn't want to user MSAL as part of script, so I simply use Invoke-RestMethod.

$body = 'grant_type=password' + `
'&client_id=<client id>' + `
'&username=<user>@<yourdomain>.onmicrosoft.com' +`
'&password=<user password>' +`
'&resource=<resource i.e. https://graph.microsoft.com>' +`
'&client_secret=<client secret>' +`
'&scope=<score i.e. User.Read>'
$token = (Invoke-RestMethod -Method Post -Uri https://login.microsoftonline.com/common/oauth2/token -Body $body).access_token
Enter fullscreen mode Exit fullscreen mode

Top comments (0)