In this article, I have included a script that uses Azure PowerShell Module to authenticate to Microsoft Graph API in PowerShell using Interactive Login.
Here are the steps:
- Install Azure AD PowerShell Module on your windows machine (if not installed already)
- Make sure Microsoft.IdentityModel.Clients.ActiveDirectory.dll and Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll are available on your windows machine
- Update your dll paths, tenant id, tenant name and site relative path in the script
- Execute script
- Use interactive login method and PowerShell client id to get an access token from ADAL
- Use access token to call the Microsoft Graph API to get site id for the given site relative path
I would like to thank Vardhaman Deshpande, for the sample PowerShell Script.
PowerShell Script
$Global:adDllPath = "C:\Program Files (x86)\WindowsPowerShell\Modules\Azure\5.1.2\StorSimple\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$Global:adWinFormsDllPath = "C:\Program Files (x86)\WindowsPowerShell\Modules\Azure\5.1.2\StorSimple\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"
# Tenant specific values
$Global:spoTenantName = "YourTenantName"
$Global:spoTenantId = "YourTenantID"
$siteRelativePath = "/sites/dev"
# Let us use a well know Client Id known to Azure AD and reserved for PowerShell.
$Global:clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$Global:graphApiEndPointUrl = "https://graph.microsoft.com"
$Global:redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$Global:spoAdminUrl = "https://$Global:spoTenantName-admin.SharePoint.com"
$Global:authority = "https://login.microsoftonline.com/$Global:spoTenantId"
function GetAuthResult {
[System.Reflection.Assembly]::LoadFrom($Global:adDllPath) | Out-Null
[System.Reflection.Assembly]::LoadFrom($Global:adWinFormsDllPath) | Out-Null
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $Global:authority
$authResult = $authContext.AcquireToken($Global:graphApiEndPointUrl, $Global:clientId, $Global:redirectUri, "Auto")
return $authResult
}
function GetSiteId {
Param(
[Parameter(Mandatory = $true)]
[String]
$Authorization,
[Parameter(Mandatory = $true)]
[String]
$SiteRelativePath
)
$endpoint = "$Global:graphApiEndPointUrl/v1.0/sites/$Global:spoTenantName.sharepoint.com:$SiteRelativePath"
$headers = @{
'Content-Type' = 'application/json'
'Authorization' = $Authorization
}
$siteResult = (Invoke-RestMethod -Method Get -Uri $endpoint -Headers $headers)
return $siteResult
}
$authResult = GetAuthResult
if ($authResult.AccessToken) {
$authorization = "Bearer {0}" -f $authResult.AccessToken
$siteResult = GetSiteId $authorization $siteRelativePath
if ($siteResult.id) {
Write-Host $siteResult.id
}
else {
Write-Host $siteResult
}
}
else {
Write-Host $authResult
}