detecting-oauth-token-theft
Detects and responds to OAuth token theft and replay attacks in cloud environments, focusing on Microsoft Entra ID (Azure AD) token protection, conditional access policies, and sign-in anomaly detection. Covers access token theft, refresh token replay, Primary Refresh Token (PRT) abuse, and pass-the-cookie attacks. Activates for requests involving OAuth token theft detection, token replay prevention, Azure AD conditional access token protection, or cloud identity attack investigation.
What this skill does
# Detecting OAuth Token Theft
## When to Use
- Investigating alerts for impossible travel or anomalous token usage in Microsoft Entra ID
- Responding to a suspected session hijacking or pass-the-cookie attack
- Configuring proactive defenses against OAuth token theft in an Azure/M365 environment
- Detecting OAuth device code phishing campaigns that bypass MFA
- Analyzing sign-in logs for token replay indicators
- Implementing Token Protection conditional access policies to bind tokens to devices
**Do not use** for on-premises Kerberos ticket attacks (pass-the-ticket, golden ticket); use Active Directory-specific investigation techniques for those scenarios.
## Prerequisites
- Microsoft Entra ID P2 license (required for Identity Protection risk detections and conditional access)
- Global Administrator or Security Administrator role in the Entra admin center
- Microsoft Defender for Cloud Apps (MDCA) license for session anomaly detection
- Access to Entra ID Sign-in Logs and Audit Logs (requires Diagnostic Settings configured to Log Analytics or Sentinel)
- Familiarity with OAuth 2.0 authorization flows (authorization code, device code, client credentials)
- Microsoft Sentinel or equivalent SIEM ingesting Entra ID sign-in and audit logs
## Workflow
### Step 1: Understand the Token Theft Attack Surface
Identify which token types are at risk and how they are stolen:
```
Token Type | Lifetime | Theft Vector | Impact
----------------------|-------------|----------------------------------|------------------
Access Token | 60-90 min | Memory dump, proxy interception | API access for token lifetime
Refresh Token | Up to 90 days| Browser cookie theft, malware | Persistent access, new access tokens
Primary Refresh Token | Session-based| Mimikatz, AADInternals, malware | Full SSO to all M365/Azure apps
Session Cookie | Varies | XSS, browser exploit, AitM proxy | Full session hijacking
Device Code Token | 15 min auth | Phishing (device code flow abuse)| Attacker gets refresh token via social engineering
```
Common attack techniques:
- **AitM Phishing (Adversary-in-the-Middle)**: Attacker proxies the legitimate login page via tools like Evilginx2, capturing session cookies and tokens after the user completes MFA
- **Device Code Phishing**: Attacker generates a device code, sends it to the victim via email/Teams, victim authenticates, attacker receives the token
- **PRT Extraction**: Attacker with local admin on a device extracts the Primary Refresh Token using Mimikatz (`sekurlsa::cloudap`) or AADInternals
- **Browser Cookie Theft**: Malware or infostealer exfiltrates browser cookies containing session tokens
### Step 2: Configure Entra ID Sign-in Risk Detection
Enable Identity Protection to flag anomalous token usage:
```
Entra Admin Center > Protection > Identity Protection > Risk Detections
Key risk detections for token theft:
- Anomalous Token : Token has unusual characteristics (claim anomalies)
- Token Issuer Anomaly : Token issued by an unusual token issuer
- Unfamiliar Sign-in : Sign-in from a location not seen before for the user
- Impossible Travel : Sign-ins from geographically distant locations in impossible time
- Malicious IP Address : Sign-in from a known malicious IP
- Suspicious Browser : Sign-in from a suspicious or attacker-controlled browser
```
Configure risk-based conditional access:
```
Entra Admin Center > Protection > Conditional Access > New Policy
Policy Name: "Block High-Risk Sign-ins - Token Theft Protection"
Assignments:
Users: All users (exclude break-glass accounts)
Cloud Apps: All cloud apps
Conditions:
Sign-in Risk: High
Grant:
Block access
Policy Name: "Require MFA for Medium-Risk Sign-ins"
Assignments:
Users: All users
Cloud Apps: All cloud apps
Conditions:
Sign-in Risk: Medium
Grant:
Require multifactor authentication
Require password change
```
### Step 3: Enable Token Protection (Preview)
Configure Token Protection to bind sign-in session tokens to the device:
```
Entra Admin Center > Protection > Conditional Access > New Policy
Policy Name: "Enforce Token Protection for Desktop Sessions"
Assignments:
Users: All users (start with a pilot group)
Cloud Apps: Office 365 Exchange Online, Office 365 SharePoint Online
Conditions:
Device Platforms: Windows
Session:
Require token protection for sign-in sessions (Preview): Enabled
Grant:
Require device to be marked as compliant
OR Require Hybrid Azure AD joined device
```
Token Protection ensures that access tokens are cryptographically bound to the device's Trusted Platform Module (TPM). If an attacker steals a token and replays it from a different device, the token is rejected because the proof-of-possession key does not match.
### Step 4: Detect Token Replay in Sign-in Logs
Query Entra sign-in logs for indicators of token theft:
```kusto
// KQL query for Microsoft Sentinel or Log Analytics
// Detect sign-ins where the token was issued in one location and used in another
SigninLogs
| where TimeGenerated > ago(7d)
| where RiskDetail contains "token" or RiskEventTypes_V2 has "anomalousToken"
| project TimeGenerated, UserPrincipalName, IPAddress, Location,
RiskDetail, RiskLevelDuringSignIn, AppDisplayName,
DeviceDetail, ClientAppUsed, TokenIssuerType
| sort by TimeGenerated desc
// Detect impossible travel with token reuse
SigninLogs
| where TimeGenerated > ago(7d)
| where ResultType == 0 // Successful sign-ins only
| summarize Locations=make_set(Location), IPs=make_set(IPAddress),
Count=count() by UserPrincipalName, bin(TimeGenerated, 1h)
| where array_length(Locations) > 1
| sort by TimeGenerated desc
// Detect device code flow abuse (often used in phishing)
SigninLogs
| where TimeGenerated > ago(7d)
| where AuthenticationProtocol == "deviceCode"
| project TimeGenerated, UserPrincipalName, IPAddress, Location,
AppDisplayName, DeviceDetail, ResultType
| sort by TimeGenerated desc
// Detect token replay: same token used from multiple IPs
AADNonInteractiveUserSignInLogs
| where TimeGenerated > ago(7d)
| where ResultType == 0
| summarize IPs=make_set(IPAddress), IPCount=dcount(IPAddress)
by UserPrincipalName, CorrelationId
| where IPCount > 1
| sort by IPCount desc
```
### Step 5: Investigate and Respond to Token Theft
When a token theft event is detected, follow this response procedure:
```powershell
# Step 5a: Revoke all refresh tokens for the compromised user
# Microsoft Graph PowerShell
Connect-MgGraph -Scopes "User.ReadWrite.All"
Revoke-MgUserSignInSession -UserId "[email protected]"
# Step 5b: Force password reset
Update-MgUser -UserId "[email protected]" -PasswordProfile @{
ForceChangePasswordNextSignIn = $true
}
# Step 5c: Review and revoke OAuth app consent grants
# Check for malicious app consent (common post-compromise persistence)
Get-MgUserOauth2PermissionGrant -UserId "[email protected]" |
Select-Object ClientId, ConsentType, Scope
# Remove suspicious OAuth grants
Remove-MgOauth2PermissionGrant -OAuth2PermissionGrantId "<grant-id>"
# Step 5d: Review enterprise app registrations for rogue apps
Get-MgServicePrincipal -Filter "displayName eq 'Suspicious App'" |
Select-Object AppId, DisplayName, SignInAudience
# Step 5e: Check for mail forwarding rules (common post-compromise action)
Get-MgUserMailFolderRule -UserId "[email protected]" -MailFolderId "Inbox" |
Where-Object { $_.Actions.ForwardTo -ne $null -or $_.Actions.RedirectTo -ne $null }
```
### Step 6: Implement Continuous Access Evaluation (CAE)
Enable CAE to revoke tokens in near-real-time when conditions change:
```
Entra Admin Center > Protection > Conditional Access > Continuous Access Evaluation
Settings:
Strictly enforce location policies: Enabled
CAE ensures that when you revoke a user's session or change their
risk level, the enforcement happens within minutes rather than waRelated in Ads & Marketing
ads
IncludedMulti-platform paid advertising audit and optimization skill. Analyzes Google, Meta, YouTube, LinkedIn, TikTok, Microsoft, and Apple Ads. 250+ checks with scoring, parallel agents, industry templates, and AI creative generation.
banana
IncludedAI image generation Creative Director powered by Google Gemini Nano Banana models. Use this skill for ANY request involving image creation, editing, visual asset production, or creative direction. Triggers on: generate an image, create a photo, edit this picture, design a logo, make a banner, visual for my anything, and all /banana commands. Handles text-to-image, image editing, multi-turn creative sessions, batch workflows, and brand presets.
rpg-migration-analyzer
IncludedAnalyzes legacy RPG (Report Program Generator) programs from AS/400 and IBM i systems for migration to modern Java applications. Extracts business logic from RPG III/IV/ILE source code, identifies data structures (D-specs), file operations (F-specs), program dependencies (CALLB/CALLP), and converts RPG constructs to Java equivalents. Generates migration reports, complexity estimates, and Java implementation strategies with POJO classes, JPA entities, and service methods. Use when modernizing AS/400 or IBM i legacy systems, analyzing RPG source files (.rpg, .rpgle, .RPGLE), converting RPG to Java, mapping data specifications to Java classes, planning legacy system migration, or when user mentions RPG analysis, Report Program Generator, RPG III/IV/ILE, AS/400 modernization, IBM i migration, packed decimal conversion, or mainframe application rewrite.
brand-library-architect
IncludedBuild a complete brand library for a product — visual asset render pipeline, brand documentation set (BRAND, COPY, MANIFESTO, BIOS, FAQ, GLOSSARY, TONE, PRICING), open-source convention files (README, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT), and a self-contained press kit. This skill should be used when the user asks to "build a brand library / brand kit / press kit / brand assets" for a product, "set up a brand library workflow," "create a positioning manifesto plus visual identity," or any combination of brand documentation + visual asset pipeline. Apply phase-by-phase or run end-to-end. Templates are product-agnostic and use {{TOKEN}} placeholders the skill prompts the user to fill.
writing-tech-post
IncludedAuthors engineering blog posts end-to-end: launch deep-dives, incident postmortems, architecture migrations, performance case studies, tutorials, AI/agent system writeups, security disclosures, and research-to-product translations. Picks the correct archetype, plans the abstraction ladder, enforces an evidence cadence (diagrams, benchmarks, profiles, traces, code, ablations), tunes voice against publisher house styles (Datadog, Vercel, GitHub, AWS, Meta, Cloudflare, Jane Street), and runs a pre-publish gate for narrative momentum and disclosure ethics. Use when drafting a new engineering post, restructuring a draft that feels flat, deciding which evidence form belongs where, validating that depth and product context are balanced, or preparing a postmortem, migration, or performance narrative for external publication. Do not use for API reference documentation, README authoring, marketing copy, release notes, generic SEO content, ghost-written executive thought leadership, or non-engineering long-form essays.
blog-google
IncludedGoogle API integration for blog performance: PageSpeed Insights, CrUX Core Web Vitals with 25-week history, Search Console performance, URL Inspection, Indexing API, GA4 organic traffic, NLP entity analysis for E-E-A-T, YouTube video search for embedding, and Google Ads Keyword Planner. Progressive feature availability based on credential tier (API key, OAuth/service account, GA4, Ads). Shares config with claude-seo at ~/.config/claude-seo/google-api.json. Use when user says "google data", "page speed", "core web vitals", "search console", "indexation", "GA4", "keyword research", "nlp entities", "blog performance", "youtube search", "google api setup".