Connect to Defender 365 Security API Using PowerShell

In this Microsoft Defender 365 Security API blog post, we will show how to connect to Defender 365 using REST API with PowerShell and programmatically manage it.

Microsoft Defender 365 allows IT departments to secure and protect their Microsoft 365 infrastructure and services with advanced security capabilities that cover endpoints, applications and data.

The Microsoft Defender Security API gives us access to all the available services using REST API protocol and lets us programmatically monitor and automate security incidents and alerts.

Access the API

To access the API, we first need to create an App Registration in Azure AD that will allow us to access Defender 365 programmatically.

In the API permissions section, we need to select the following permissions.

In the Request APO permissions, select

APIs my organization uses

Search for:

Microsoft threat protection

In the select permissions, select the desired permissions.

Once you have the permissions set, use the following PowerShell code. The code will request a token and list the top 100 alerts.

PowerShell Code

# Get Token 

$tenantId = '' # Tenant ID
$appId = '' # Application ID
$appSecret = '' #Application Secret

$resourceAppIdUri = 'https://graph.microsoft.com/'
$oAuthUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"
$body = [Ordered] @{
    resource = "$resourceAppIdUri"
    client_id = "$appId"
    client_secret = "$appSecret"
    grant_type = 'client_credentials'
}
$response = Invoke-RestMethod -Method Post -Uri $oAuthUri -Body $body -ErrorAction Stop
$aadToken = $response.access_token


$url = "https://graph.microsoft.com/v1.0/security/alerts_V2?$top=100&$skip=200"
$headers = @{ 
    'Content-Type' = 'application/json'
    Accept = 'application/json'
    Authorization = "Bearer $aadToken" 
}
# Run REST API


$webResponse = Invoke-WebRequest -Method Get -Uri $url -Headers $headers  -ErrorAction Stop
$response =  $webResponse | ConvertFrom-Json

foreach ($item in $response){
 
  foreach ($x in $item.value)
   {
     Write-Host $x.title
     write-host $x.description


   }

}


Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.