Intermediate โฑ 100 min ๐Ÿ“‹ 14 Steps

Investigate Risky OAuth Apps & Service Accounts

Audit OAuth app permissions, identify over-privileged applications, create policies for risky consent grants, investigate suspicious app behaviour, revoke access from compromised apps, and remediate compromised service accounts.

๐Ÿ“‹ Overview

About This Lab

OAuth applications are the silent attack surface of modern enterprises. Every time a user clicks “Allow” on a consent prompt, they may be granting a third-party application access to corporate data in Exchange, SharePoint, OneDrive, or Teams. Illicit consent grants and overprivileged OAuth apps are increasingly exploited in supply-chain attacks, credential harvesting, and data exfiltration campaigns. Defender for Cloud Apps provides a comprehensive inventory of all OAuth apps connected to your tenant, their permissions, publisher verification status, and data access patterns.

๐Ÿข Enterprise Use Case

A security operations team discovers that a marketing survey tool granted itself Mail.ReadWrite and Files.ReadWrite.All permissions through a user consent flow. The app, from an unverified publisher, has been accessing 200+ mailboxes and downloaded 8 GB of SharePoint data overnight. Simultaneously, three service accounts with application-level permissions show login activity from unexpected IP addresses. The team must identify all risky OAuth apps, revoke unauthorized access, create preventative policies, and investigate the extent of data exposure.

๐ŸŽฏ What You Will Learn

  1. Navigate the OAuth apps dashboard and understand the app inventory
  2. Identify overprivileged apps with high-risk permission scopes
  3. Assess app risk using publisher verification and community usage
  4. Investigate app data access patterns and anomalous behaviour
  5. Create OAuth app policies for automatic detection of risky consent
  6. Configure alert policies for unusual app behaviour
  7. Revoke app permissions and ban malicious applications
  8. Investigate compromised service accounts via activity logs
  9. Remediate compromised credentials and rotate secrets
  10. Configure user consent settings to prevent future illicit consent
  11. Create an admin consent workflow for controlled app approval
  12. Build app governance policies for ongoing compliance
  13. Integrate findings with Defender XDR incidents
  14. Generate executive reports on OAuth app risk posture

๐Ÿ”‘ Why This Matters

OAuth-based attacks bypass traditional security controls: they don’t involve malware, don’t trigger endpoint alerts, and use legitimate API calls that blend with normal traffic. A single overprivileged OAuth app can read every email in your organisation without triggering any traditional security alert. In 2024, Microsoft observed a 300% increase in illicit consent grant attacks targeting Microsoft 365 tenants.

โš™๏ธ Prerequisites

  • Licensing: Microsoft Defender for Cloud Apps (standalone or via Microsoft 365 E5)
  • Portal Access: Security Administrator or Cloud App Security Administrator role
  • Entra ID: Application Administrator role for managing app registrations and consent settings
  • Microsoft 365 connector: Connected and operational (from Lab 01)
  • App connectors: Configured (from Lab 02)
  • Test OAuth apps: At least 2–3 OAuth apps consented in your tenant for investigation practice

Step 1 ยท Navigate the OAuth Apps Dashboard

The OAuth apps page provides a comprehensive inventory of all third-party applications that have been granted access to your Microsoft 365 tenant through OAuth consent.

Access the OAuth Apps Page

  1. Navigate to security.microsoft.com > Cloud Apps > OAuth apps
  2. Review the dashboard summary: total apps, apps with high privilege, apps from unverified publishers
  3. Use the filter bar to sort by Permission level: High, Medium, Low
  4. Filter by Publisher verification: show only apps from unverified publishers
  5. Note the Community use column: apps with low community adoption are higher risk
๐Ÿ’ก Pro Tip: Sort by Permission level: High and Community use: Uncommon to quickly identify the highest-risk apps. An app with high permissions and low community adoption is a strong indicator of a targeted or malicious application.

Step 2 ยท Identify Overprivileged Applications

Overprivileged apps request more permissions than they need for their stated purpose. Identify these apps and assess whether their permissions are justified.

Audit High-Privilege Permissions

  1. In the OAuth apps page, filter by Permission level: High
  2. Click on each app to view the detailed Permissions tab
  3. Flag apps with dangerous permission scopes: Mail.ReadWrite, Files.ReadWrite.All, Directory.ReadWrite.All, User.ReadWrite.All
  4. Compare the app’s stated purpose (from the publisher description) against the permissions requested
  5. Document which apps are legitimately high-privilege (e.g., backup solutions) vs. overprivileged
# ---------------------------------------------------------------
# PURPOSE: List all OAuth apps in your tenant that hold high-privilege
#          delegated permissions (ReadWrite, FullControl, or All scopes).
# WHY: Overprivileged OAuth apps are the silent attack surface of M365.
#      An app with Mail.ReadWrite can read/modify every email; one with
#      Files.ReadWrite.All can access every file in SharePoint/OneDrive.
#      This script identifies those apps for review and potential revocation.
# PREREQUISITES: Install-Module Microsoft.Graph -Scope CurrentUser
#      Requires Application.Read.All permission.
# OUTPUT: Table showing AppName, AppId, Publisher, and the high-privilege
#         Scopes granted. Apps from unknown publishers with broad scopes
#         (e.g. "Mail.ReadWrite User.ReadWrite.All") are highest priority.
# ---------------------------------------------------------------
Connect-MgGraph -Scopes "Application.Read.All"

# Iterate over every service principal (app) in the tenant.
Get-MgServicePrincipal -All | ForEach-Object {
    $sp = $_
    # Get all OAuth2 delegated permission grants for this app.
    $grants = Get-MgServicePrincipalOAuth2PermissionGrant -ServicePrincipalId $sp.Id -All
    # Filter to only grants that include dangerous scope keywords.
    $highPriv = $grants | Where-Object { $_.Scope -match "ReadWrite|FullControl|All" }
    if ($highPriv) {
        [PSCustomObject]@{
            AppName = $sp.DisplayName       # App/service principal display name
            AppId   = $sp.AppId             # Application (client) ID
            Publisher = $sp.PublisherName    # Publisher - "" means unverified
            Scopes  = ($highPriv.Scope | Select-Object -Unique) -join ", "  # Granted scopes
        }
    }
} | Format-Table -AutoSize

Step 3 ยท Assess Publisher Verification and Risk

Publisher verification is a critical trust signal. Verified publishers have completed the Microsoft Partner Network attestation process, while unverified publishers have not proven their identity.

  1. Filter the OAuth apps list by Publisher: Not verified
  2. For each unverified app, review: how many users consented, when was it first seen, what data has it accessed
  3. Cross-reference with the app publisher’s website and privacy policy
  4. Check the Last activity column to identify dormant apps that still hold permissions
  5. Mark apps for investigation, ban, or approve based on your assessment
โš ๏ธ Important: An unverified publisher does not automatically mean malicious. Many legitimate small vendors have not gone through the verification process. However, unverified apps with high permissions and low community usage should be investigated thoroughly.

Step 4 ยท Investigate App Data Access Patterns

Review how much data each app has accessed and whether the access patterns are consistent with the app’s stated purpose.

  1. Click on a high-risk app in the OAuth apps page
  2. Navigate to the Activity tab to see all API calls made by the app
  3. Review the Data usage section: total data volume accessed, files read, emails accessed
  4. Look for anomalous patterns: bulk downloads outside business hours, access to executive mailboxes, unexpected SharePoint site access
  5. Use the Activity log to filter by the app’s service principal and review detailed API call logs
  6. Document suspicious findings for remediation
// ---------------------------------------------------------------
// PURPOSE: Investigate a suspicious OAuth app's activity in Defender XDR
//          Advanced Hunting to determine what data it accessed.
// WHY: When you identify a suspicious app in the OAuth dashboard,
//      you need to understand: how many API calls it made, how much
//      data it accessed, and how many mailboxes/accounts it touched.
//      This helps determine if data was exfiltrated.
// HOW TO USE: Replace "SuspiciousAppName" with the app's display name.
//      Run in Defender XDR > Hunting > Advanced hunting.
// OUTPUT COLUMNS:
//   ActionType - the API operation (e.g. MailItemsAccessed, FileDownloaded)
//   Timestamp (1d bins) - shows activity pattern over 30 days
//   TotalActivities - number of API calls per day per action type
//   DataAccessedMB - total data volume accessed (in megabytes)
//   UniqueMailboxes - distinct accounts the app touched
// RED FLAGS: High DataAccessedMB outside business hours, or
//   UniqueMailboxes far exceeding the app's stated purpose.
// ---------------------------------------------------------------
CloudAppEvents
| where Timestamp > ago(30d)
| where Application == "SuspiciousAppName"
| summarize TotalActivities = count(),
            DataAccessedMB = sum(ActivityObjects.Size) / 1048576,
            UniqueMailboxes = dcount(AccountObjectId)
    by ActionType, bin(Timestamp, 1d)
| order by Timestamp desc

Step 5 ยท Create OAuth App Policies for Risky Consent

Create automated policies that detect and alert on risky OAuth consent grants as they happen.

  1. Navigate to Cloud Apps > Policies > Policy management
  2. Click + Create policy > OAuth app policy
  3. Name the policy: Alert on High-Privilege Consent from Unverified Publishers
  4. Set filters: Permission level equals High AND Publisher equals Not verified
  5. Set Actions: Notify (send alert to SOC team)
  6. Optionally enable Revoke app for automatic remediation
  7. Click Create
๐Ÿ’ก Pro Tip: Create multiple policies with increasing severity: Monitor for medium-risk consent, Alert for high-risk, and Auto-revoke for critical patterns (e.g., apps requesting Mail.ReadWrite from unverified publishers with zero community adoption).

Step 6 ยท Configure Anomaly Detection for App Behaviour

Enable built-in anomaly detection policies that use machine learning to identify unusual app behaviour patterns.

  1. Navigate to Cloud Apps > Policies > Policy management
  2. Filter by Type: Anomaly detection to see built-in policies
  3. Enable Unusual addition of credentials to an OAuth app
  4. Enable Misleading OAuth app name
  5. Enable Misleading publisher name for an OAuth app
  6. Review and enable OAuth app redirect URL anomaly
  7. Configure alert severity and notification settings for each policy

Step 7 ยท Revoke App Permissions and Ban Malicious Apps

When you identify a malicious or overprivileged app, revoke its permissions and ban it to prevent future consent.

  1. In the OAuth apps page, click on the target app
  2. Click the Revoke app button to immediately remove all granted permissions
  3. Click Ban app to prevent users from consenting to this app in the future
  4. Review the list of users who consented and notify them about the revocation
  5. Check the Activity log to determine if data was exfiltrated before revocation
# ---------------------------------------------------------------
# PURPOSE: Revoke all delegated permissions from a malicious OAuth app
#          and disable its service principal to prevent further access.
# WHY: When an app is confirmed malicious (e.g. exfiltrating data),
#      you must immediately remove its permissions AND disable it.
#      Simply revoking permissions isn't enough - the app could
#      re-request consent. Disabling the service principal blocks
#      all authentication and API access.
# STEPS:
#   1. Remove all OAuth2 delegated permission grants
#   2. Disable the service principal (AccountEnabled = false)
# OUTPUT: Confirmation message with the disabled app's display name.
# WARNING: Verify the app is not used for legitimate automation
#          before disabling - this will break any workflows using it.
# ---------------------------------------------------------------
$appId = "malicious-app-client-id"  # The Application (client) ID to revoke

# Look up the service principal by its application ID.
$servicePrincipal = Get-MgServicePrincipal -Filter "AppId eq '$appId'"

# Step 1: Remove every delegated permission grant for this app.
# This immediately revokes all user-consented scopes.
Get-MgServicePrincipalOAuth2PermissionGrant -ServicePrincipalId $servicePrincipal.Id -All |
    ForEach-Object { Remove-MgOAuth2PermissionGrant -OAuth2PermissionGrantId $_.Id }

# Step 2: Disable the service principal so it cannot authenticate at all.
# Even if permissions are re-granted, the app cannot sign in while disabled.
Update-MgServicePrincipal -ServicePrincipalId $servicePrincipal.Id -AccountEnabled:$false

Write-Host "App revoked and disabled: $($servicePrincipal.DisplayName)"
โš ๏ธ Important: Revoking an app may break legitimate business workflows if the app is used for automation or integration. Always verify the app’s business use before revoking. Coordinate with app owners and have a rollback plan.

Step 8 ยท Investigate Compromised Service Accounts

Service accounts with application-level permissions are high-value targets. Investigate service accounts showing suspicious activity.

  1. Navigate to Cloud Apps > Activity log
  2. Filter by User type: Application to isolate service principal activities
  3. Look for sign-ins from unexpected IP addresses or geographies
  4. Review activities performed: bulk file access, new credential additions, role assignment changes
  5. Cross-reference with Entra ID sign-in logs for the service principal
  6. Document indicators of compromise (IOCs): IP addresses, timestamps, data accessed
# ---------------------------------------------------------------
# PURPOSE: Investigate service principal (non-human) sign-ins to
#          detect compromised service accounts.
# WHY: Service principals with application-level permissions are
#      high-value targets. If an attacker compromises a service
#      account's client secret, they can silently access mailboxes,
#      files, and directories. Unusual IP addresses or geolocations
#      in sign-in logs are strong indicators of compromise.
# PREREQUISITES: AuditLog.Read.All permission in Microsoft Graph.
# OUTPUT: Table of the 50 most recent service principal sign-ins
#         showing timestamp, service name, IP address, location
#         (city + country), and sign-in status.
# RED FLAGS: Sign-ins from unexpected countries, Tor exit nodes,
#   VPN services, or IPs not in your data centre ranges.
# ---------------------------------------------------------------
Connect-MgGraph -Scopes "AuditLog.Read.All"

# Query Entra ID sign-in logs for service principal authentications.
# servicePrincipalId ne null filters out user sign-ins.
Get-MgAuditLogSignIn -Filter "servicePrincipalId ne null" -Top 50 |
    Select-Object CreatedDateTime, ServicePrincipalName, IpAddress,
        @{N='Location';E={$_.Location.City + ', ' + $_.Location.CountryOrRegion}},
        Status |
    Format-Table -AutoSize

Step 9 ยท Remediate Compromised Credentials

When a service account or OAuth app is confirmed compromised, immediately rotate credentials and remove unauthorized access.

  1. Rotate all client secrets and certificates for the compromised app registration
  2. Review and remove any unauthorized credentials added by the attacker
  3. Disable the service principal while investigating
  4. Review all app role assignments and remove unauthorized roles
  5. Check for new app registrations created by the compromised identity
  6. Enable continuous access evaluation (CAE) to revoke tokens in near-real-time
# ---------------------------------------------------------------
# PURPOSE: Rotate (replace) all client secrets for a compromised
#          app registration and issue a new short-lived secret.
# WHY: When an app registration's credentials are compromised, the
#      attacker holds valid secrets. You must:
#      1. Delete ALL existing secrets (including attacker-added ones)
#      2. Create a fresh secret with a shorter lifetime (6 months)
#      3. Update all legitimate services using this app's credentials
# IMPORTANT: After running this script, immediately update the secret
#   in all applications, key vaults, or CI/CD pipelines that use it.
#   The old secrets are instantly invalid - dependent systems will break.
# OUTPUT: The new secret value (shown only once). Copy it immediately;
#         it cannot be retrieved again from Entra ID.
# ---------------------------------------------------------------
$appObjectId = "your-app-object-id"  # The Object ID of the app registration

# Step 1: Remove ALL existing client secrets (passwords).
# This invalidates any secrets the attacker may have stolen or added.
Get-MgApplicationPassword -ApplicationId $appObjectId | ForEach-Object {
    Remove-MgApplicationPassword -ApplicationId $appObjectId -KeyId $_.KeyId
}

# Step 2: Create a new secret with a descriptive name and 6-month expiry.
# Shorter lifetimes limit exposure if this secret is also compromised.
$newSecret = Add-MgApplicationPassword -ApplicationId $appObjectId -PasswordCredential @{
    DisplayName = "Rotated-$(Get-Date -Format 'yyyyMMdd')"  # Date-stamped for audit trail
    EndDateTime = (Get-Date).AddMonths(6)                    # Expires in 6 months
}

# CRITICAL: This is the ONLY time the secret value is visible.
# Store it in Azure Key Vault - never in code or config files.
Write-Host "New secret created. Value: $($newSecret.SecretText)"
Write-Host "Update all applications using this secret immediately."

Step 10 ยท Configure User Consent Settings

Restrict user consent to prevent future illicit consent grants. Configure Entra ID to limit which apps users can consent to independently.

  1. Navigate to Entra ID > Enterprise applications > Consent and permissions
  2. Under User consent settings, select Allow user consent for apps from verified publishers, for selected permissions
  3. Select only low-risk permissions: openid, profile, email, User.Read
  4. Set Group owner consent to Do not allow
  5. Save the settings

Step 11 ยท Set Up Admin Consent Workflow

Create a structured approval process for apps requiring permissions beyond user consent limits.

  1. Navigate to Entra ID > Enterprise applications > Admin consent requests
  2. Enable the Admin consent request workflow
  3. Designate approvers (e.g., Security team, IT governance team)
  4. Set Request expiry to 30 days
  5. Configure email notifications for new consent requests
  6. Document the approval criteria: publisher verification, permission justification, business need

Step 12 ยท Build App Governance Policies for Compliance

Create comprehensive app governance policies that enforce compliance standards across all OAuth apps in your tenant.

  1. Create a policy to alert on apps with Application permissions (vs. delegated) accessing Mail or Files APIs
  2. Create a policy to detect apps inactive for 90+ days that still hold high-privilege permissions
  3. Create a policy for new apps accessing more than 100 users’ data within the first 7 days
  4. Configure weekly digest reports for app governance findings

Step 13 ยท Integrate with Defender XDR Incidents

MDA OAuth app alerts automatically correlate with Defender XDR incidents, providing cross-product context for investigations.

  1. Navigate to Incidents & alerts in the Defender XDR portal
  2. Filter by Service source: Microsoft Defender for Cloud Apps
  3. Review incidents that correlate OAuth app alerts with identity and endpoint signals
  4. Use the Attack story to see the full timeline: from initial consent to data exfiltration
  5. Document the investigation and apply remediation actions from within the incident

Step 14 ยท Generate Executive Risk Reports

Create reports that communicate OAuth app risk posture to leadership and demonstrate security value.

  1. Export the OAuth apps list with risk scoring and permission levels
  2. Summarize key metrics: total apps, high-risk apps, apps revoked, policies in place
  3. Include trend data from the policy activity logs
  4. Provide recommendations: consent restrictions, app lifecycle management, quarterly reviews
  5. Schedule recurring quarterly reports for the security governance committee

Summary

What You Accomplished

  • Audited all OAuth apps in your tenant and identified overprivileged applications
  • Assessed publisher verification and community usage risk signals
  • Investigated suspicious app data access patterns
  • Created OAuth app policies for automated risky consent detection
  • Revoked and banned malicious applications
  • Investigated and remediated compromised service accounts
  • Configured user consent restrictions and admin consent workflows
  • Integrated OAuth app findings with Defender XDR incidents

Next Steps

๐Ÿ“š Documentation Resources

ResourceDescription
Manage OAuth appsInvestigate and manage connected OAuth applications
OAuth app policiesCreate policies to detect risky OAuth consent grants
Configure user consentRestrict user consent settings in Entra ID
Admin consent workflowSet up admin approval for app consent requests
Investigate risky OAuth appsInvestigation procedures for suspicious OAuth apps
โ† Previous Lab Next Lab โ†’