Skip to content
All posts

Detection & Response

Illicit OAuth Consent in Microsoft 365: Detect and Lock Down

One click on Accept gives an attacker's app a user's mail, and a password reset does not end it. Our lab, a tuned consent detection, and how to lock it down.

HHHuzaifa HafeezChief Technology Officer

· 13 min read

On this page

A user clicks a link to "view a shared document", sees a genuine Microsoft sign-in page, and clicks Accept on a permissions prompt. No password is stolen and MFA works exactly as designed. An app the attacker registered in their own tenant can now read that user's mail and files, and it keeps that access after the user changes their password.

This is illicit consent, or consent phishing. It is quiet, because the user's own account does the granting and the audit trail looks like normal app use. This post shows the OAuth step that is abused, a lab we built (a small OAuth server, fourteen days of Entra audit records, and a detection tuned from four false positives to none), and how to remove a grant and lock consent down.

Microsoft 365 lets third-party apps read data through Microsoft Graph. To do that on a user's behalf, the app needs delegated permissions, and someone has to approve them. That approval is consent. Microsoft's documentation on configuring user consent states the default plainly: "all users are allowed to consent to applications for permissions that don't require administrator consent". The Graph permissions reference lists Mail.Read, Mail.Send and Files.Read.All as delegated permissions that do not require admin consent. So on that setting, an ordinary user can hand an outside app their mailbox and every file they can open. Defaults change over time, so check your own tenant.

The assumption that breaks is "if we reset the password, the attacker is out". With consent phishing the attacker never had the password. They hold tokens issued to their app, backed by a grant in your directory. Microsoft's own guide to illicit consent grants says it directly: resetting passwords or requiring MFA "aren't effective against this type of attack, because these apps are external to the organization".

MITRE ATT&CK tracks this as Steal Application Access Token (T1528) and the use of the tokens as Application Access Token (T1550.001).

This is not the same problem as a stolen session. In our post on stolen-session sign-ins the attacker replays the user's tokens, and the fix is device binding. Here the tokens belong to the attacker's app from the start, so device checks do not apply.

The protocol step that grants it

Consent rides on the normal OAuth 2.0 authorisation code grant (RFC 6749, section 4.1). The client sends the user to the authorisation endpoint with a client_id, redirect_uri and scope. The server signs the user in, asks for a decision, and redirects back with a code, which the client swaps for tokens. Nothing here is a vulnerability. The abuse lives in three parameters:

  • scope decides what the user is asked to approve. A phishing app asks for Mail.Read, Files.Read.All and similar. Microsoft's scopes documentation adds that offline_access returns a refresh token that is "typically valid for 90 days", and that "if any delegated permission is granted, offline_access is implicitly granted".
  • prompt=consent forces the prompt even if consent exists. Without it, a user who has already consented sees no prompt at all on the next visit.
  • redirect_uri is where the code goes: the attacker's server, registered in the attacker's own tenant.

To show the persistence rather than describe it, we wrote a minimal OAuth server in Python (authz_mock.py, about 100 lines, on 127.0.0.1 only). It stores grants per app and user, separately from the password, and applies a user consent policy: "allow user consent for apps" or "verified publishers, low-impact permissions only". Its confidential-client refresh tokens follow Microsoft's refresh token revocation table. walk_consent.py plays the client and prints each message. Tokens are random strings, not JWTs.

huzaifa@futaqsec: ~/oauth-consent
$ python3 walk_consent.py
# 1. first visit: user consent policy = legacy (allow user consent for apps)
GET /oauth2/v2.0/authorize?client_id=a3f1c2d4-0000-4c11-9e2b-7d5e00000001
&response_type=code
&redirect_uri=https%3A%2F%2Fdocs-viewer.example.net%2Fauth%2Fcallback
&scope=openid%20offline_access%20User.Read%20Mail.Read%20Files.Read.All
&state=x1
&prompt=consent
<- 302 prompt: consent prompt shown: Files.Read.All Mail.Read User.Read offline_access openid
POST /token grant_type=authorization_code <- 200 scope='Files.Read.All Mail.Read User.Read offline_access openid' access_token=at.Ga9Xao1... refresh_token=rt.BzPq2qf...
# 2. user changes own password; the app is a confidential client
[after password change] POST /token grant_type=refresh_token <- 200 new access_token=at.TYv6Iue...
# 3. admin revokes the user's sessions (revokeSignInSessions)
{'ok': True, 'grants_left': 1}
[after revoke] POST /token grant_type=refresh_token <- 400 refresh token revoked
# 4. user opens the same link again next week (no prompt=consent this time)
GET /oauth2/v2.0/authorize?client_id=a3f1c2d4-0000-4c11-9e2b-7d5e00000001
&response_type=code
&redirect_uri=https%3A%2F%2Fdocs-viewer.example.net%2Fauth%2Fcallback
&scope=openid%20offline_access%20User.Read%20Mail.Read%20Files.Read.All
&state=x1
<- 302 silent: existing grant covers all scopes, no prompt shown
POST /token grant_type=authorization_code <- 200 scope='Files.Read.All Mail.Read User.Read offline_access openid' access_token=at.Yl3EiWb... refresh_token=rt.Spqd-ox...
# 5. remove the delegated grant, then tighten the policy to microsoft-user-default-low
[after grant removed] POST /token grant_type=refresh_token <- 400 no consent grant
GET /oauth2/v2.0/authorize?client_id=a3f1c2d4-0000-4c11-9e2b-7d5e00000001
&response_type=code
&redirect_uri=https%3A%2F%2Fdocs-viewer.example.net%2Fauth%2Fcallback
&scope=openid%20offline_access%20User.Read%20Mail.Read%20Files.Read.All
&state=x1
&prompt=consent
<- 403 needs_admin: user consent not allowed by policy microsoft-user-default-low
Our mock authorisation server, driven by walk_consent.py. Real output from our lab; tokens are truncated by the script.

Each step maps to a defender's decision:

  1. One click is enough. The user approves exactly the scopes in the URL. The refresh token goes to the attacker's server.
  2. A password change does not end it. Microsoft's table shows that tokens issued to a confidential client (a web app with its own secret) "stay alive" when the user changes their password, uses self-service reset, or an admin resets it in the Azure portal. They are revoked by a reset in the Entra or Microsoft 365 admin centre, or by revoking the user's refresh tokens. Our mock models only the user's own change.
  3. Revoking sessions breaks the current refresh token. It does not touch the grant (grants_left: 1).
  4. So access comes back silently. Next time the user follows any link to that app, there is no prompt, and the attacker gets fresh tokens.
  5. Only removing the grant ends it, and only the consent policy stops the user granting it again. In the last line the same request is refused and turned into an admin request.

That fourth step is easy to miss. A runbook that revokes sessions and resets the password looks complete, and the grant is still there.

Building the audit log lab

We had no real tenant to phish, and would not use real users' logs, so gen_audit.py writes fourteen days of Entra audit records for five invented users at example.com, shaped like the Sentinel AuditLogs table. We took the field names from Microsoft's own Sentinel rules in the Azure-Sentinel repository: ConsentContext.IsAdminConsent, ConsentAction.Permissions (which carries ConsentType and Scope inside one string), DelegatedPermissionGrant.Scope, AppRole.Value and AppAddress. The operation names match Microsoft's audit activity reference.

A single consent writes up to three records that share a CorrelationId: Add service principal (the first time the app appears in your tenant), Add delegated permission grant, and Consent to application. Admin consent to application permissions adds Add app role assignment to service principal.

The benign activity is the noise that breaks naive rules, a mix typical of small and mid-sized tenants:

  • Meetly Scheduler, a verified-publisher calendar app, consented by four users for Calendars.ReadWrite.
  • InboxZen for Outlook, a verified-publisher email plug-in, consented by two users for Mail.ReadWrite.
  • ExpenseFlow, tenant-wide admin consent by the IT administrator, including Files.Read.All and the application permission User.Read.All, with a change record.
  • Microsoft Graph Command Line Tools, first-party. The administrator consents for himself to DelegatedPermissionGrant.ReadWrite.All.
  • HR Portal, an app registered in our own tenant, User.Read only.
  • PDF Merge Online, an unverified external tool, Files.ReadWrite, one user. Not malicious, not sanctioned.

Then two attacks. On day eleven, Zara and Faisal consent to Docs Secure Viewer sixteen minutes apart, after the same lure. On day thirteen, Usman consents to Payroll Q4 Review, which asks for Mail.Read, MailboxSettings.ReadWrite and Contacts.Read. All three come from the users' own browsers, so IPs and user agents look normal.

huzaifa@futaqsec: ~/oauth-consent
$ python3 gen_audit.py
wrote 37 audit records over 14 days, 5 users, 8 apps
1 Add app role assignment to service principal
14 Add delegated permission grant
8 Add service principal
14 Consent to application
$ python3 show_inventory.py
Meetly Scheduler publisher=Meetly Ltd owner=external reply=https://app.meetly.example.com/oauth
InboxZen for Outlook publisher=InboxZen Inc owner=external reply=https://api.inboxzen.example.com/callback
ExpenseFlow publisher=ExpenseFlow Software owner=external reply=https://login.expenseflow.example.com/signin
Microsoft Graph Command Line Tools publisher=- owner=Microsoft reply=http://localhost
HR Portal publisher=- owner=our tenant reply=https://hr.example.com/signin-oidc
PDF Merge Online publisher=- owner=external reply=https://pdfmerge.example.org/auth
Docs Secure Viewer publisher=- owner=external reply=https://docs-viewer.example.net/auth/callback
Payroll Q4 Review publisher=- owner=external reply=https://hr-review.example.net/oauth/cb
Writing the lab data set, then the service principal inventory we join against later. Real output.

This is the part of a malicious consent record that matters, trimmed from one of the lab's records:

{
  "OperationName": "Consent to application",
  "InitiatedBy": { "user": { "userPrincipalName": "zara.ali@example.com", "ipAddress": "192.0.2.10" } },
  "TargetResources": [{
    "type": "ServicePrincipal", "displayName": "Docs Secure Viewer",
    "modifiedProperties": [
      { "displayName": "ConsentContext.IsAdminConsent", "newValue": "\"False\"" },
      { "displayName": "ConsentAction.Permissions",
        "newValue": "\"[] => [[... ConsentType: Principal, Scope:  openid offline_access User.Read Mail.Read Files.Read.All, ...]]; \"" }
    ]
  }]
}

Two things are not in the record: publisher verification and the app's owner tenant. Those live on the service principal (verifiedPublisher, appOwnerOrganizationId). So the lab also writes sp_inventory.json, the kind of daily service principal export you would load into Sentinel as a watchlist.

The first rule, and the four false positives

We started from Microsoft's own list. The app consent investigation playbook names the delegated permission families most misused in consent phishing: Mail.* (but not Mail.ReadBasic*), Contacts.*, MailboxSettings.*, People.*, Files.*, Notes.*, Directory.AccessAsUser.All and user_impersonation. Microsoft says its responders see combinations of the first six in 99% of consent phishing attacks. We added scopes that manage other apps' permissions, plus anything ending .ReadWrite.All. Rule v1 fires on any successful consent that includes one of them.

huzaifa@futaqsec: ~/oauth-consent
$ python3 detect.py v1
== rule v1 (any consent with a high-impact scope): 8 alert(s), 3/3 attack consents, 4 false positive(s), 1 unsanctioned
[-] 2026-11-11T11:05:00Z faisal.noor@example.com InboxZen for Outlook admin=False risky=Mail.ReadWrite,MailboxSettings.Read
[-] 2026-11-13T10:30:00Z kamran.it@example.com ExpenseFlow admin=True risky=Files.Read.All
[-] 2026-11-14T14:02:00Z kamran.it@example.com Microsoft Graph Command Line Tools admin=False risky=Application.Read.All,DelegatedPermissionGrant.ReadWrite.All
[!] 2026-11-16T16:21:00Z ayesha.tariq@example.com PDF Merge Online admin=False risky=Files.ReadWrite
[-] 2026-11-18T15:40:00Z usman.sheikh@example.com InboxZen for Outlook admin=False risky=Mail.ReadWrite,MailboxSettings.Read
[+] 2026-11-19T08:47:00Z zara.ali@example.com Docs Secure Viewer admin=False risky=Mail.Read,Files.Read.All
[+] 2026-11-19T09:03:00Z faisal.noor@example.com Docs Secure Viewer admin=False risky=Mail.Read,Files.Read.All
[+] 2026-11-21T19:12:00Z usman.sheikh@example.com Payroll Q4 Review admin=False risky=Mail.Read,MailboxSettings.ReadWrite,Contacts.Read
Rule v1 against the fourteen days. [+] attack, [-] false positive, [!] unsanctioned but not malicious. Real output.

It caught all three attack consents, and raised four false positives in two weeks from five users. At a few hundred staff that is a daily queue nobody reads.

Scopes could not separate them: the attack apps and InboxZen asked for almost the same thing. What separated them was who published the app. Every false positive came from an app that was publisher-verified, published by Microsoft, or covered by a change record. Every attack came from an unverified app owned by a tenant we had never seen. The audit record alone cannot tell you that. You need the join.

The tuned rule

Rule v2 splits consent into two cases. For user consent, alert only when the app is untrusted: no verified publisher, and not owned by your tenant or by Microsoft. For admin consent, alert unless the app is on a short list of approved changes, because a tenant-wide grant should always have a ticket behind it. Severity goes up to High when the app asks for offline_access together with mail access, or when more than one user consents to the same untrusted app within 24 hours, which is what a phishing wave looks like.

def trusted(c):
    sp = inv.get(c["sp"])            # not in the export yet: treat as untrusted
    if not sp: return False
    return bool(sp["verifiedPublisher"]["displayName"]) or sp["appOwnerOrganizationId"] in (OUR_TENANT, MSFT_TENANT)

for c in all_c:
    if not c["risky"]: continue
    if c["admin"]:
        if app_id(c) in APPROVED_ADMIN_CONSENTS: continue        # admin consent with a change record
        c["sev"] = "High"; v2.append(c); continue
    if trusted(c): continue                                       # verified publisher, our tenant or Microsoft
    peers = {o["user"] for o in all_c if o["sp"] == c["sp"] and abs(ts(o) - ts(c)) <= timedelta(hours=24)}
    mail = any(s.startswith(("Mail.", "MailboxSettings.")) for s in c["risky"])
    c["sev"] = "High" if ("offline_access" in c["scopes"] and (mail or len(peers) > 1)) else "Medium"
    v2.append(c)

An app missing from the inventory counts as untrusted. A brand-new malicious app will never be in yesterday's export, so the rule fails towards alerting.

huzaifa@futaqsec: ~/oauth-consent
$ python3 detect.py v2
== rule v2 (untrusted app + high-impact scope; unapproved admin consent): 4 alert(s), 3/3 attack consents, 0 false positive(s), 1 unsanctioned
[!] Medium 2026-11-16T16:21:00Z ayesha.tariq@example.com PDF Merge Online admin=False risky=Files.ReadWrite
[+] High 2026-11-19T08:47:00Z zara.ali@example.com Docs Secure Viewer admin=False risky=Mail.Read,Files.Read.All
[+] High 2026-11-19T09:03:00Z faisal.noor@example.com Docs Secure Viewer admin=False risky=Mail.Read,Files.Read.All
[+] High 2026-11-21T19:12:00Z usman.sheikh@example.com Payroll Q4 Review admin=False risky=Mail.Read,MailboxSettings.ReadWrite,Contacts.Read
$ python3 detect.py v2 --no-approvals | head -2
== rule v2 (untrusted app + high-impact scope; unapproved admin consent): 5 alert(s), 3/3 attack consents, 1 false positive(s), 1 unsanctioned
[-] High 2026-11-13T10:30:00Z kamran.it@example.com ExpenseFlow admin=True risky=Files.Read.All
Rule v2 on the same data, then a check that the admin-consent branch still fires without its approval list. Real output.

All three attack consents are High, with no false positives on this data. PDF Merge Online stays at Medium, which we think is right: an unverified outside app has write access to a user's files. That is a conversation with the user, not noise. The --no-approvals run shows the admin branch is live: without its change record, ExpenseFlow fires as High.

The same logic in KQL

We had no live Sentinel workspace for this lab, so we tested the logic in Python on the generated logs (above) and translated it to KQL, parsing fields the way Microsoft's published rules do. SpInventory is a watchlist built from a daily export of Get-MgServicePrincipal -All with the appId, verifiedPublisher and appOwnerOrganizationId properties. Run it report-only for a week before you alert on it.

// Consent to an untrusted app for a high-impact scope, or admin consent without a change record
let OurTenant = "11111111-2222-4333-8444-555555555555";        // replace with your tenant ID
let MicrosoftTenant = "f8cdef31-a31e-4b4a-93e4-5f571e91255a";  // owner tenant of Microsoft first-party apps
let ApprovedAdminConsents = dynamic(["0b6d1a2e-0000-4a00-8000-000000000103"]);  // appIds with a change record
let RiskyScope = @"^(Mail\.|Contacts\.|MailboxSettings\.|People\.|Files\.|Notes\.|Sites\.|Directory\.AccessAsUser\.All|Application\.|DelegatedPermissionGrant\.|AppRoleAssignment\.|RoleManagement\.|.*\.ReadWrite\.All$)";
let Inventory = _GetWatchlist('SpInventory')
    | project SpId = tostring(id), AppId = tostring(appId),
              Publisher = tostring(verifiedPublisher), Owner = tostring(appOwnerOrganizationId);
let Consents = AuditLogs
    | where TimeGenerated > ago(1d)
    | where OperationName == "Consent to application" and Result =~ "success"
    | extend Target = TargetResources[0]
    | extend SpId = tostring(Target.id), App = tostring(Target.displayName),
             User = tostring(InitiatedBy.user.userPrincipalName), IP = tostring(InitiatedBy.user.ipAddress)
    | mv-apply p = Target.modifiedProperties on (
        summarize Props = make_bag(bag_pack(tostring(p.displayName), trim('"', tostring(p.newValue)))))
    | extend IsAdmin = tostring(Props["ConsentContext.IsAdminConsent"]) == "True",
             Scopes = split(trim(" ", extract(@"Scope:\s+([^,\]]*)", 1, tostring(Props["ConsentAction.Permissions"]))), " ")
    | mv-apply s = Scopes to typeof(string) on (
        where s matches regex RiskyScope and not(s startswith "Mail.ReadBasic")
        | summarize Risky = make_set(s))
    | where array_length(Risky) > 0
    | join kind=leftouter Inventory on SpId
    | extend Trusted = isnotempty(Publisher) or Owner in (OurTenant, MicrosoftTenant);
let Wave = Consents | summarize Users = dcount(User) by SpId;
Consents
| join kind=leftouter Wave on SpId
| where (IsAdmin and not(AppId in (ApprovedAdminConsents))) or (not(IsAdmin) and not(Trusted))
| extend Severity = case(IsAdmin, "High",
         set_has_element(Scopes, "offline_access") and (tostring(Risky) has "Mail." or Users > 1), "High",
         "Medium")
| project TimeGenerated, User, IP, App, AppId, IsAdmin, Risky, Users, Severity, CorrelationId

Where the rule is blind

  • Verified does not mean safe. In January 2023 Microsoft reported a consent phishing campaign in which "the actor used fraudulent partner accounts to add a verified publisher to OAuth app registrations". Keep verified-publisher consents in a weekly review.
  • The inventory lags. A legitimate verified app consented to before the next export will alert once. Refresh the watchlist more often, or accept that.
  • It sees the grant, not the use. The app's later Graph calls show in Graph activity and service principal sign-in logs. That is a separate hunt.
  • A compromised administrator can grant tenant-wide consent and add the app to your approval list. Protect the list as you would a privileged role.

Responding when it fires

When we work one of these alerts, the order is: stop new tokens, remove the grant, revoke what was issued, then scope the damage. Microsoft's playbook recommends disabling a malicious app rather than deleting it, because "if you only delete the application, it might return later if another user grants consent". The cmdlets come from Microsoft's pages on reviewing and revoking permissions, disabling user sign-in for an app and revoking user access. We could not run them without a live tenant, so test them in yours before you need them.

Connect-MgGraph -Scopes "Application.ReadWrite.All","DelegatedPermissionGrant.ReadWrite.All","AppRoleAssignment.ReadWrite.All","User.RevokeSessions.All"

$sp = Get-MgServicePrincipal -Filter "appId eq 'a3f1c2d4-0000-4c11-9e2b-7d5e00000001'"

# 1. Stop the app getting new tokens, for every user, without deleting it
Update-MgServicePrincipal -ServicePrincipalId $sp.Id -AccountEnabled:$false

# 2. Remove every delegated grant the app holds, and any application permissions
Get-MgOauth2PermissionGrant -All | Where-Object { $_.ClientId -eq $sp.Id } |
    ForEach-Object { Remove-MgOauth2PermissionGrant -OAuth2PermissionGrantId $_.Id }
Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -All |
    ForEach-Object { Remove-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -AppRoleAssignmentId $_.Id }

# 3. Revoke refresh tokens for each user who consented (from the alert)
"zara.ali@example.com","faisal.noor@example.com" | ForEach-Object { Revoke-MgUserSignInSession -UserId $_ }

Then scope the damage from the audit and mailbox logs: what the app touched, and any new inbox rules or forwarding. Microsoft warns this needs mailbox auditing switched on before the attack. Finally, find the lure. Two users consented sixteen minutes apart, so others probably received it. This is where measuring reporting, not clicks pays off.

Detection tells you a grant happened. The consent policy decides whether it can happen at all. Move user consent from Allow user consent for apps (microsoft-user-default-legacy) to Allow user consent for apps from verified publishers, for selected permissions (microsoft-user-default-low). Then classify which permissions count as low impact. Microsoft's permission classification page suggests starting with openid, profile, email and offline_access, plus User.Read if your apps need it.

 PATCH https://graph.microsoft.com/v1.0/policies/authorizationPolicy
 {
   "defaultUserRolePermissions": {
     "permissionGrantPoliciesAssigned": [
-      "managePermissionGrantsForSelf.microsoft-user-default-legacy",
+      "managePermissionGrantsForSelf.microsoft-user-default-low",
       "managePermissionGrantsForOwnedResource.DeveloperConsent"
     ]
   }
 }

Read the current policy first and keep any managePermissionGrantsForOwnedResource.* entries, or you may remove developer consent you rely on. The change affects only future consent; existing grants stay, so pair it with a one-off review of every grant.

Next, turn on the admin consent workflow (Enterprise apps > Consent and permissions > Admin consent settings). Without it, the stricter policy just blocks people and they find workarounds. With it, requests go to named reviewers, and that review becomes the change record behind rule v2's approval list.

ControlWhat it does against consent phishingLimits
User consent: verified publishers, low-impact permissionsA user can no longer grant Mail.Read to an unknown appNeeds permission classification; verified status can be abused
Admin consent workflowTurns a blocked consent into a reviewed requestReviewers need time and a checklist
Risk-based step-up consentMicrosoft escalates risky requests to admin consent; per the publisher verification overview, it blocks user consent to most unverified multi-tenant apps registered after November 2020Only acts while user consent is on; Microsoft decides what counts as risky
Consent detection (rule v2)Catches what the policy still allows, and admin consent without a ticketSees the grant, not the use
Regular grant reviewFinds old grants made before the policy changedManual unless scripted

For a small or mid-sized tenant, the first two rows close most of the gap in an afternoon. The detection still matters, because verified apps and administrators can still consent. When we build identity monitoring as part of managed detection and response, consent grants are one of the first audit events we tune. The rule is short. The tuning is a list of the apps that tenant actually trusts.

Checklist

  • Entra AuditLogs are streamed to your SIEM, and you can find Consent to application events.
  • A service principal inventory (verified publisher, owner tenant) is exported daily and joined to consent events.
  • An alert fires on user consent to untrusted apps for mail, file, contact or directory scopes.
  • Admin consent without a change record raises a High alert.
  • Your runbook disables the service principal and removes grants, not only the user's sessions.
  • User consent is set to verified publishers with low-impact permissions, and the admin consent workflow is on.
  • Existing grants have been reviewed once, with AllPrincipals grants to non-Microsoft apps checked first.

Tooling and references

  • OAuth
  • Entra ID
  • Detection Engineering
  • Phishing
HH

Written by

Huzaifa Hafeez

Chief Technology Officer, FutaqSec

Keep reading

Detection & Response12 min read

Detecting Stolen-Session Sign-ins in Microsoft Entra ID

A replayed session already carries MFA. We built a lab of Entra sign-in logs, tuned a detection from 15 false positives to none, and show what stops replay.

Huzaifa Hafeez

Not sure where to start?

A 30-minute scoping call is enough to understand your environment and recommend the right first step. No obligation.

Book a free consultation