Listen to this Post

Introduction:
Non-human identities (NHIs)—service principals, service accounts, and OAuth apps—now outnumber human identities by a staggering 82 to 1, yet they remain the most neglected frontier in enterprise security. Unlike human users, NHIs operate programmatically, cannot be enrolled in multi-factor authentication, and typically retain standing privileges granted at creation and never revisited. Microsoft Defender now brings NHIs into the same unified platform where security teams already protect human identities, delivering purpose-built capabilities for discovery, risk assessment, governance, threat detection, and attack disruption.
Learning Objectives:
- Understand the six integrated focus areas of Microsoft Defender’s NHI protection: Visibility, Risk Analysis, Relationship Mapping, Governance Policies, AI Agent Awareness, and Detection & Disruption
- Learn how to discover, assess, and remediate risky non-human identities across Entra ID, Active Directory, and SaaS applications
- Master practical commands and techniques for auditing service accounts, managing OAuth app permissions, and implementing least-privilege access for NHIs
You Should Know:
1. Visibility: Discovering the Invisible Identity Estate
The fundamental challenge with NHIs is that security teams simply cannot answer basic questions: How many exist? Which are still in use? Which hold excessive permissions? Microsoft Defender consolidates visibility across Entra service principals, Active Directory service accounts, and SaaS-connected OAuth apps into a single identity inventory.
Step-by-Step Guide to Auditing NHIs:
For Entra ID Service Principals (Azure/Windows PowerShell):
Connect to Microsoft Graph
Connect-MgGraph -Scopes "Application.Read.All", "Directory.Read.All"
List all service principals with creation date and app ownership
Get-MgServicePrincipal | Select-Object DisplayName, AppId, CreatedDateTime,
@{N="Owners";E={Get-MgServicePrincipalOwner -ServicePrincipalId $_.Id}}
Identify service principals with high privileges (Global Administrator, etc.)
Get-MgDirectoryRole | ForEach-Object {
$role = $_
Get-MgDirectoryRoleMember -DirectoryRoleId $role.Id |
Where-Object {$_.AdditionalProperties.'@odata.type' -eq "microsoft.graph.servicePrincipal"}
}
For Active Directory Service Accounts (Windows Server):
Find all service accounts (accounts with SPN or servicePrincipalName set)
Get-ADUser -Filter {ServicePrincipalName -1e "$null"} -Properties ServicePrincipalName,
PasswordLastSet, AccountExpirationDate, Enabled
Identify stale service accounts (not logged in for 90+ days)
$staleDate = (Get-Date).AddDays(-90)
Get-ADUser -Filter {Enabled -eq $true} -Properties LastLogonDate |
Where-Object {$<em>.LastLogonDate -lt $staleDate -or $</em>.LastLogonDate -eq $null}
For OAuth Apps (Google Workspace – using GAM CLI):
List all OAuth apps with access to Google Workspace gam print tokens | grep -E "clientId|scope|user" Identify apps with high-risk scopes (Gmail, Drive full access) gam print tokens | grep -E "https://www.googleapis.com/auth/gmail|https://www.googleapis.com/auth/drive"
2. Risk Analysis and Identity Risk Scoring
Defender surfaces critical risk signals: Unused Identities, Over-Privileged Identities, High-Privileged Identities, and an Identity Risk Score for NHIs. Research shows 90% of NHI tokens have excessive permissions, and 44% of tokens are exposed in the wild.
Step-by-Step Risk Assessment:
Audit Over-Privileged Service Principals:
List service principals with directory roles (high privilege)
Get-MgDirectoryRole | ForEach-Object {
$role = $_
$members = Get-MgDirectoryRoleMember -DirectoryRoleId $role.Id
$members | Where-Object {$_.AdditionalProperties.'@odata.type' -eq "microsoft.graph.servicePrincipal"} |
Select-Object @{N="RoleName";E={$role.DisplayName}}, Id
}
Check Microsoft Graph API permissions granted to each app
Get-MgServicePrincipal -All | ForEach-Object {
$app = $_
$perms = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $app.Id
if ($perms) {
Write-Host "App: $($app.DisplayName) - Permissions: $($perms.Count)" -ForegroundColor Yellow
}
}
Check for Unused/Stale NHIs in Azure:
Azure CLI - List service principals with no recent activity
az ad sp list --all --query "[?createdDateTime<='2025-01-01']" --output table
Check sign-in activity for service principals (Azure CLI)
az monitor activity-log list --query "[?contains(claims.clientId, '{app-id}')]" --output table
3. Relationship Mapping: Understanding Dependencies
Defender maps relationships: what application depends on this identity, who owns it, what resources can it access, and with what permissions. This dependency mapping is critical because NHIs are often shared across multiple workloads, and AI agents increasingly ride on existing service principals, making them indistinguishable from routine integrations.
Step-by-Step Dependency Mapping:
Find Application Dependencies on Service Principals (Azure):
Find all applications using a specific service principal
$spId = "your-service-principal-id"
Get-MgApplication | Where-Object {
$app = $_
$owners = Get-MgApplicationOwner -ApplicationId $app.Id
$owners.Id -contains $spId
} | Select-Object DisplayName, AppId
List all resources a service principal can access (Azure RBAC)
az role assignment list --assignee "{service-principal-id}" --include-inherited --output table
Map Active Directory Service Account Dependencies:
Find services running under a specific service account
Get-WmiObject Win32_Service | Where-Object {$_.StartName -eq "DOMAIN\service_account"} |
Select-Object Name, DisplayName, State
Find scheduled tasks using a service account
Get-ScheduledTask | Where-Object {$_.Principal.UserId -eq "DOMAIN\service_account"}
4. Governance Policies: Automated Risk Remediation
Organizations can define policies leveraging Defender insights—unused timeframe, privilege level, risk score, over-privilege status, and AI agent association—and map them to automated disablement of identities that exceed acceptable risk.
Step-by-Step Governance Implementation:
Create Conditional Access Policy for NHIs (Azure Portal / PowerShell):
Create a policy to block high-risk service principals (using Microsoft Graph)
$policy = @{
displayName = "Block High-Risk Service Principals"
description = "Automatically block NHIs with risk score > 70"
conditions = @{
applications = @{
includeApplications = @("All")
}
users = @{
includeUsers = @("All")
excludeUsers = @()
}
servicePrincipalRiskLevels = @("high", "medium")
}
grantControls = @{
operator = "OR"
builtInControls = @("block")
}
state = "enabled"
}
Note: This requires Microsoft Entra ID P2 licensing
Automate Service Account Password Rotation (PowerShell):
Rotate service account password and update dependent services
$newPassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 32 | % {[bash]$_})
$account = Get-ADUser -Identity "service_account_name"
Set-ADAccountPassword -Identity $account -1ewPassword (ConvertTo-SecureString $newPassword -AsPlainText -Force)
Update all services using this account
Get-WmiObject Win32_Service | Where-Object {$<em>.StartName -eq "DOMAIN\service_account"} | ForEach-Object {
$service = $</em>
$service.Change($null, $null, $null, $null, $null, $null, $newPassword, $null)
}
5. AI Agent Awareness: The New Attack Surface
Many AI agents operate using traditional NHIs provisioned for other workloads, making them indistinguishable from routine integrations at the identity layer. Every AI agent needs an identity to function—accessing data, invoking APIs, and taking action autonomously at machine speed. Without proper governance, agents can become the new vector for credential theft and lateral movement.
Step-by-Step AI Agent Identity Audit:
Detect AI Agent Activity in Azure AD Logs:
Azure CLI - Query sign-in logs for unusual service principal activity (high frequency, off-hours) az monitor activity-log list --query "[?claims.clientId] | [?contains(claims.clientId, 'agent')]" --output table Check for automated pattern in service principal sign-ins (potential AI agent) az monitor activity-log list --query "[?claims.clientId] | group_by(claims.clientId, &[bash].claims.clientId)" --output table
Identify Service Principals Used by AI Agents (PowerShell):
Look for service principals with high API call volume (suspicious of AI agents)
Get-MgServicePrincipal -All | ForEach-Object {
$sp = $_
$signIns = Get-MgAuditLogSignIn -Filter "appId eq '$($sp.AppId)'" -Top 1000
if ($signIns.Count -gt 500) {
Write-Host "High-volume SP: $($sp.DisplayName) - $($signIns.Count) sign-ins" -ForegroundColor Red
}
}
6. Detection and Disruption: Stopping NHI-Based Attacks
Defender detects anomalous and malicious activity involving NHIs using behavioral analytics and Microsoft’s global threat intelligence. Attackers exploit NHIs for persistent, stealthy access—Midnight Blizzard demonstrated how compromised NHIs enable lateral movement across cloud resources without triggering user-centric controls like MFA.
Step-by-Step NHI Threat Detection:
Monitor for Anomalous Service Principal Activity (Azure Sentinel / Log Analytics):
// Detect service principal sign-ins from unusual locations AADServicePrincipalSignInLogs | where TimeGenerated > ago(7d) | summarize Locations = dcount(Location), Total = count() by AppId, UserPrincipalName | where Locations > 3 | project AppId, UserPrincipalName, Locations, Total // Detect service principal sign-ins outside business hours AADServicePrincipalSignInLogs | where TimeGenerated !between (datetime(08:00) .. datetime(18:00)) | project TimeGenerated, AppId, UserPrincipalName, IPAddress, Location
Detect Lateral Movement via NHIs (Windows Event Logs):
Check for suspicious service account logins (Event ID 4624)
Get-WinEvent -FilterHashtable @{LogName='Security'; ID=4624} |
Where-Object {$<em>.Properties[bash].Value -like "service"} |
Select-Object TimeCreated, @{N='Account';E={$</em>.Properties[bash].Value}},
@{N='SourceIP';E={$<em>.Properties[bash].Value}} |
Group-Object Account | Where-Object {$</em>.Count -gt 50}
Disrupt Compromised NHIs:
Immediately disable a compromised service account
Disable-ADAccount -Identity "compromised_service_account"
Revoke all active sessions for a service principal (Microsoft Graph)
Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/{id}/revokeSignInSessions"
Rotate credentials for OAuth app
(Azure Portal: App Registrations > Certificates & Secrets > New Client Secret)
What Undercode Say:
- Key Takeaway 1: NHIs are no longer a niche concern—they are the majority identity type in most enterprises, yet 90% have excessive permissions and 44% have exposed credentials. The visibility gap between human and non-human identity management is the single largest unaddressed risk in modern security architectures.
-
Key Takeaway 2: Microsoft Defender’s unified approach fundamentally changes the game by treating NHIs with the same rigor as human identities—discovery, risk scoring, governance policies, and automated disruption are now available in a single pane of glass. The integration of AI agent awareness is particularly critical as autonomous agents proliferate faster than governance frameworks can adapt.
Analysis: The cybersecurity industry has spent decades perfecting human identity management—MFA, conditional access, risk-based authentication. Yet NHIs, which now outnumber humans 82:1, have been treated as second-class citizens. This asymmetry is exploited by attackers who know that service accounts bypass MFA, retain standing privileges, and rarely have their permissions reviewed. Microsoft’s move to bring NHIs into Defender represents a fundamental shift: recognizing that in the AI era, the “invisible workforce” of bots, agents, and automation scripts is the primary attack surface. The six focus areas—Visibility, Risk Analysis, Relationship Mapping, Governance, AI Awareness, and Detection—directly address the NHI lifecycle from creation to decommissioning. For security teams, this means finally having the tools to answer “how many NHIs do we have?” and “which ones are risky?” without manual, error-prone processes. The automated governance policies are particularly powerful—moving from reactive incident response to proactive, policy-driven risk reduction.
Prediction:
- +1 Organizations that adopt Defender’s unified NHI protection within the next 12-18 months will reduce identity-based breach risk by 60-70%, as automated governance eliminates the “standing privilege” problem that has historically enabled lateral movement.
-
+1 The convergence of NHI protection with AI agent governance will become the dominant security narrative in 2026-2027, as regulators begin mandating identity audits for all autonomous systems—turning compliance into a competitive differentiator.
-
-1 Organizations that delay NHI governance will face increasingly sophisticated attacks that exploit AI agents as persistence mechanisms—attackers will compromise one service account, use it to spawn malicious AI agents, and operate autonomously for months without detection.
-
-1 The “shadow AI” problem—developers provisioning agents without security oversight—will create a new class of NHI-related breaches that dwarf traditional human identity attacks in scale and impact, as each compromised agent becomes a beachhead for further compromise.
-
+1 Microsoft’s investment in behavioral analytics for NHIs will establish a new industry standard—NHI activity monitoring will become as routine as user behavior analytics (UBA) is today, with SIEM and XDR platforms racing to add native NHI detection capabilities.
▶️ Related Video (80% Match):
https://www.youtube.com/watch?v=2qc3ANMj1VI
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Markolauren Defender – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


