- Published on
Request an Access Token to query Microsoft Defender for Identity APIs
- Authors
- Name
- Jonathan Devere-Ellery
Recently I was wanting to query Microsoft Defender for Identity through PowerShell. Both Graph APIs and PowerShell modules are planned and on the roadmap, but until these are released the options are fairly limited.
In this case I want to use MSAL to handle the authentication for me. First I'll go ahead and load a MSAL library into the session using an existing module I already have installed.
$ExoModule = Get-Module -Name "ExchangeOnlineManagement" -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
$MSAL = Join-Path $ExoModule.ModuleBase "NetFramework\Microsoft.Identity.Client.dll"
Try {Add-Type -LiteralPath $MSAL | Out-Null} Catch {}
I normally use the EXO module, but this can also easily be the Graph SDK module if you already have the Microsoft.Graph.Applications
module installed.
$MgAuthModule = Get-Module -Name "Microsoft.Graph.Authentication" -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
$MSAL = Join-Path $MgAuthModule.ModuleBase "Dependencies\Desktop\Microsoft.Identity.Client.dll"
Try {Add-Type -LiteralPath $MSAL | Out-Null} Catch {}
Next comes building application that will be used to make the request:
$AppId = '7b7531ad-5926-4f2d-8a1d-38495ad33e17' # Azure Advanced Threat Protection 1st party application ID
$ClientId = '29d9ed98-a469-4536-ade2-f981bc1d605e' # Microsoft Authentication Broker
$Scopes = New-Object System.Collections.Generic.List[string]
$Scopes.Add("$AppId/.default")
$pubApp = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($AppId).WithClientId($ClientId).WithRedirectUri('urn:ietf:wg:oauth:2.0:oob').Build()
Lastly comes the actual request for a token:
$MDIToken = $pubApp.AcquireTokenInteractive($Scopes).ExecuteAsync().GetAwaiter().GetResult()
# Alternatively we can add methods such as login hint
$MDIToken = $pubApp.AcquireTokenInteractive($Scopes).WithLoginHint("admin@contoso.onmicrosoft.com").ExecuteAsync().GetAwaiter().GetResult()
We can validate the result of our token using $AccessToken
and that it contains the necessary scopes.
Now that we have a valid access token, we can use it to make requests to the (undocumented) APIs for Defender for Identity using standard Invoke-RestMethod
calls. Take care that these APIs will be deprecated at some point.
$WorkspaceName = "contoso"
$uri = "https://$WorkspaceName.atp.azure.com/api/sensors"
$headers = @{
'Authorization' = "$($MDIToken.TokenType) $($MDIToken.AccessToken)"
}
Invoke-RestMethod -Uri $uri -UseBasicParsing -Headers $headers