[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GZCGGARD2AE9RP30K3FA4H":3,"skill-same:01M6GZCGGARD2AE9RP30K3FA4H":90},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":6,"ownerHtmlUrl":57,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":58,"install":59,"resources":72},"01M6GZCGGARD2AE9RP30K3FA4H","performing-oauth-scope-minimization-review",null,"Performs OAuth 2.0 scope minimization review to identify over-permissioned third-party application integrations, excessive API scopes, unused token grants, and risky OAuth consent patterns across identity providers and SaaS platforms. Activates for requests involving OAuth scope audit, API permission review, third-party app risk assessment, or consent grant minimization.","micsapp\u002Fmicstec-skills","micsapp","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F82411001?v=4","01M6GWCFQ6D3PV8EHNY62NN5VW","01M6GWCFVE1PA5HG0DKC7AMFJ3",4,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fperforming-oauth-scope-minimization-review\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"performing oauth scope minimization review","performing","scope","review","OAuth","audit","api-security","assessment","third-party-risk","api","risk assessment","access","grants","permission","across","token","app","cybersecurity","saas platforms","security","2026-11-10 10:12:30",false,"---\nname: performing-oauth-scope-minimization-review\ndescription: >\n  Performs OAuth 2.0 scope minimization review to identify over-permissioned third-party\n  application integrations, excessive API scopes, unused token grants, and risky OAuth\n  consent patterns across identity providers and SaaS platforms.\n  Activates for requests involving OAuth scope audit, API permission review, third-party\n  app risk assessment, or consent grant minimization.\ndomain: cybersecurity\nsubdomain: identity-access-management\ntags: [OAuth, scope-minimization, API-security, consent-review, third-party-risk, token-audit]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\n---\n\n# Performing OAuth Scope Minimization Review\n\n## When to Use\n\n- Annual or quarterly review of third-party application OAuth permissions\n- After a security incident involving compromised OAuth tokens or unauthorized data access\n- Compliance audit requiring documentation of third-party data access (GDPR Article 28, SOC 2)\n- Discovery of shadow IT applications accessing organizational data via OAuth grants\n- Migration or consolidation of SaaS applications requiring permission cleanup\n- Implementing least-privilege principle for API integrations\n\n**Do not use** for reviewing first-party application permissions within the same trust boundary; OAuth scope minimization focuses on third-party and cross-boundary consent grants.\n\n## Prerequisites\n\n- Admin access to identity providers (Microsoft Entra ID, Okta, Google Workspace)\n- Microsoft Graph API permissions: Application.Read.All, OAuth2PermissionGrant.ReadWrite.All\n- Inventory of approved third-party integrations from procurement or IT governance\n- OAuth scope risk classification framework\n- Tools for token analysis (jwt.io for manual review, automated scripts for bulk analysis)\n\n## Workflow\n\n### Step 1: Inventory All OAuth Grants and Consent Permissions\n\nEnumerate all OAuth application registrations and delegated permissions:\n\n```python\n\"\"\"\nOAuth Grant Inventory - Microsoft Entra ID\nEnumerates all application registrations, service principals,\nand delegated\u002Fapplication permission grants.\n\"\"\"\nimport requests\nimport json\nfrom collections import defaultdict\n\nclass EntraOAuthAuditor:\n    def __init__(self, tenant_id, client_id, client_secret):\n        self.tenant_id = tenant_id\n        self.base_url = \"https:\u002F\u002Fgraph.microsoft.com\u002Fv1.0\"\n        self.token = self._get_token(client_id, client_secret)\n        self.headers = {\"Authorization\": f\"Bearer {self.token}\"}\n\n    def _get_token(self, client_id, client_secret):\n        url = f\"https:\u002F\u002Flogin.microsoftonline.com\u002F{self.tenant_id}\u002Foauth2\u002Fv2.0\u002Ftoken\"\n        response = requests.post(url, data={\n            \"grant_type\": \"client_credentials\",\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n            \"scope\": \"https:\u002F\u002Fgraph.microsoft.com\u002F.default\"\n        })\n        return response.json()[\"access_token\"]\n\n    def get_all_service_principals(self):\n        \"\"\"Get all service principals (enterprise applications).\"\"\"\n        apps = []\n        url = f\"{self.base_url}\u002FservicePrincipals?$top=999&$select=id,appId,displayName,appOwnerOrganizationId,servicePrincipalType,accountEnabled,createdDateTime\"\n\n        while url:\n            response = requests.get(url, headers=self.headers)\n            data = response.json()\n            apps.extend(data.get(\"value\", []))\n            url = data.get(\"@odata.nextLink\")\n\n        return apps\n\n    def get_oauth2_permission_grants(self):\n        \"\"\"Get all delegated permission grants (user consent).\"\"\"\n        grants = []\n        url = f\"{self.base_url}\u002Foauth2PermissionGrants?$top=999\"\n\n        while url:\n            response = requests.get(url, headers=self.headers)\n            data = response.json()\n            grants.extend(data.get(\"value\", []))\n            url = data.get(\"@odata.nextLink\")\n\n        return grants\n\n    def get_app_role_assignments(self, sp_id):\n        \"\"\"Get application permission assignments for a service principal.\"\"\"\n        url = f\"{self.base_url}\u002FservicePrincipals\u002F{sp_id}\u002FappRoleAssignments\"\n        response = requests.get(url, headers=self.headers)\n        return response.json().get(\"value\", [])\n\n    def build_permission_inventory(self):\n        \"\"\"Build comprehensive OAuth permission inventory.\"\"\"\n        service_principals = self.get_all_service_principals()\n        delegated_grants = self.get_oauth2_permission_grants()\n\n        # Map service principal IDs to names\n        sp_map = {sp[\"id\"]: sp for sp in service_principals}\n\n        inventory = []\n\n        # Process delegated permissions\n        for grant in delegated_grants:\n            sp = sp_map.get(grant[\"clientId\"], {})\n            scopes = grant.get(\"scope\", \"\").split()\n\n            for scope in scopes:\n                if not scope:\n                    continue\n                inventory.append({\n                    \"app_name\": sp.get(\"displayName\", \"Unknown\"),\n                    \"app_id\": grant.get(\"clientId\"),\n                    \"publisher_tenant\": sp.get(\"appOwnerOrganizationId\"),\n                    \"is_third_party\": sp.get(\"appOwnerOrganizationId\") != self.tenant_id,\n                    \"permission_type\": \"Delegated\",\n                    \"scope\": scope,\n                    \"consent_type\": grant.get(\"consentType\"),  # AllPrincipals or Principal\n                    \"principal_id\": grant.get(\"principalId\"),\n                    \"granted_date\": sp.get(\"createdDateTime\"),\n                    \"is_enabled\": sp.get(\"accountEnabled\", True)\n                })\n\n        # Process application permissions\n        for sp in service_principals:\n            app_roles = self.get_app_role_assignments(sp[\"id\"])\n            for role in app_roles:\n                inventory.append({\n                    \"app_name\": sp.get(\"displayName\"),\n                    \"app_id\": sp.get(\"id\"),\n                    \"publisher_tenant\": sp.get(\"appOwnerOrganizationId\"),\n                    \"is_third_party\": sp.get(\"appOwnerOrganizationId\") != self.tenant_id,\n                    \"permission_type\": \"Application\",\n                    \"scope\": role.get(\"appRoleId\"),\n                    \"consent_type\": \"AdminConsent\",\n                    \"granted_date\": role.get(\"createdDateTime\"),\n                    \"is_enabled\": sp.get(\"accountEnabled\", True)\n                })\n\n        return inventory\n```\n\n### Step 2: Classify OAuth Scopes by Risk Level\n\nCategorize permissions based on data access sensitivity:\n\n```python\n\"\"\"\nOAuth Scope Risk Classification\nMaps API scopes to risk levels based on data sensitivity and access breadth.\n\"\"\"\n\nMICROSOFT_GRAPH_SCOPE_RISK = {\n    # CRITICAL - Full administrative or unrestricted access\n    \"critical\": {\n        \"scopes\": [\n            \"Directory.ReadWrite.All\",\n            \"RoleManagement.ReadWrite.Directory\",\n            \"Application.ReadWrite.All\",\n            \"AppRoleAssignment.ReadWrite.All\",\n            \"Mail.ReadWrite\",\n            \"Mail.Send\",\n            \"Files.ReadWrite.All\",\n            \"Sites.FullControl.All\",\n            \"User.ReadWrite.All\",\n            \"Group.ReadWrite.All\",\n            \"MailboxSettings.ReadWrite\",\n            \"full_access_as_app\",\n        ],\n        \"risk_description\": \"Can read\u002Fwrite all data, modify directory, or impersonate users\",\n        \"review_frequency\": \"Monthly\",\n        \"requires_admin_consent\": True\n    },\n    # HIGH - Broad read access or sensitive data write\n    \"high\": {\n        \"scopes\": [\n            \"Mail.Read\",\n            \"Mail.Read.Shared\",\n            \"Calendars.ReadWrite\",\n            \"Contacts.ReadWrite\",\n            \"Files.Read.All\",\n            \"Sites.Read.All\",\n            \"User.Read.All\",\n            \"Group.Read.All\",\n            \"Directory.Read.All\",\n            \"AuditLog.Read.All\",\n            \"SecurityEvents.ReadWrite.All\",\n            \"TeamSettings.ReadWrite.All\",\n        ],\n        \"risk_description\": \"Broad read access to sensitive organizational data\",\n        \"review_frequency\": \"Quarterly\",\n        \"requires_admin_consent\": True\n    },\n    # MEDIUM - Scoped data access\n    \"medium\": {\n        \"scopes\": [\n            \"Calendars.Read\",\n            \"Contacts.Read\",\n            \"Files.ReadWrite\",\n            \"Sites.ReadWrite.All\",\n            \"Tasks.ReadWrite\",\n            \"Notes.ReadWrite.All\",\n            \"Chat.ReadWrite\",\n            \"ChannelMessage.Send\",\n            \"Team.ReadBasic.All\",\n        ],\n        \"risk_description\": \"Scoped access to specific data types with write capability\",\n        \"review_frequency\": \"Semi-annually\"\n    },\n    # LOW - Minimal or user-profile only access\n    \"low\": {\n        \"scopes\": [\n            \"User.Read\",\n            \"openid\",\n            \"profile\",\n            \"email\",\n            \"offline_access\",\n            \"Calendars.Read.Shared\",\n            \"People.Read\",\n            \"User.ReadBasic.All\",\n        ],\n        \"risk_description\": \"Basic user profile or minimal scoped access\",\n        \"review_frequency\": \"Annually\"\n    }\n}\n\ndef classify_scope_risk(scope):\n    \"\"\"Classify a single OAuth scope by risk level.\"\"\"\n    for risk_level, config in MICROSOFT_GRAPH_SCOPE_RISK.items():\n        if scope in config[\"scopes\"]:\n            return {\n                \"scope\": scope,\n                \"risk_level\": risk_level,\n                \"description\": config[\"risk_description\"],\n                \"review_frequency\": config[\"review_frequency\"]\n            }\n    # Unknown scopes default to HIGH risk\n    return {\n        \"scope\": scope,\n        \"risk_level\": \"high\",\n        \"description\": \"Unknown scope - requires manual classification\",\n        \"review_frequency\": \"Quarterly\"\n    }\n\ndef analyze_app_risk(app_permissions):\n    \"\"\"Calculate aggregate risk score for an application's permissions.\"\"\"\n    risk_weights = {\"critical\": 40, \"high\": 20, \"medium\": 10, \"low\": 2}\n    total_score = 0\n    classified_scopes = []\n\n    for perm in app_permissions:\n        classification = classify_scope_risk(perm[\"scope\"])\n        classified_scopes.append(classification)\n        total_score += risk_weights.get(classification[\"risk_level\"], 10)\n\n    # Bonus risk for application (vs delegated) permissions\n    app_type_permissions = [p for p in app_permissions if p[\"permission_type\"] == \"Application\"]\n    total_score += len(app_type_permissions) * 15\n\n    # Bonus risk for admin-consented broad access\n    admin_consent = [p for p in app_permissions if p[\"consent_type\"] == \"AllPrincipals\"]\n    total_score += len(admin_consent) * 10\n\n    if total_score >= 100:\n        aggregate_risk = \"CRITICAL\"\n    elif total_score >= 60:\n        aggregate_risk = \"HIGH\"\n    elif total_score >= 30:\n        aggregate_risk = \"MEDIUM\"\n    else:\n        aggregate_risk = \"LOW\"\n\n    return {\n        \"total_score\": total_score,\n        \"aggregate_risk\": aggregate_risk,\n        \"scope_count\": len(app_permissions),\n        \"critical_scopes\": len([s for s in classified_scopes if s[\"risk_level\"] == \"critical\"]),\n        \"high_scopes\": len([s for s in classified_scopes if s[\"risk_level\"] == \"high\"]),\n        \"classified_scopes\": classified_scopes\n    }\n```\n\n### Step 3: Identify Over-Permissioned Applications\n\nDetect apps requesting more permissions than functionally needed:\n\n```python\n\"\"\"\nOver-Permission Detection\nIdentifies applications with excessive OAuth scopes relative to their function.\n\"\"\"\n\ndef detect_over_permissions(inventory, approved_apps_catalog):\n    \"\"\"\n    Compare actual permissions against approved scope catalog\n    to find over-permissioned applications.\n    \"\"\"\n    findings = []\n\n    # Group permissions by application\n    app_permissions = defaultdict(list)\n    for perm in inventory:\n        app_permissions[perm[\"app_name\"]].append(perm)\n\n    for app_name, permissions in app_permissions.items():\n        # Check against approved catalog\n        approved = approved_apps_catalog.get(app_name)\n\n        if not approved:\n            # Unknown\u002Funapproved application\n            findings.append({\n                \"app_name\": app_name,\n                \"finding_type\": \"UNAPPROVED_APPLICATION\",\n                \"severity\": \"HIGH\",\n                \"detail\": f\"Application not in approved catalog with {len(permissions)} permission grants\",\n                \"scopes\": [p[\"scope\"] for p in permissions],\n                \"recommendation\": \"Review and approve or revoke all permissions\"\n            })\n            continue\n\n        approved_scopes = set(approved.get(\"approved_scopes\", []))\n        actual_scopes = set(p[\"scope\"] for p in permissions)\n\n        # Find excessive scopes (granted but not approved)\n        excessive = actual_scopes - approved_scopes\n        if excessive:\n            risk = analyze_app_risk([p for p in permissions if p[\"scope\"] in excessive])\n            findings.append({\n                \"app_name\": app_name,\n                \"finding_type\": \"EXCESSIVE_SCOPES\",\n                \"severity\": risk[\"aggregate_risk\"],\n                \"detail\": f\"{len(excessive)} scopes beyond approved list\",\n                \"excessive_scopes\": list(excessive),\n                \"approved_scopes\": list(approved_scopes),\n                \"recommendation\": \"Remove excessive scopes or update approved catalog\"\n            })\n\n        # Find unused scopes (approved but activity logs show no API calls)\n        # This requires API activity log correlation\n        unused = approved_scopes - actual_scopes\n        if unused:\n            findings.append({\n                \"app_name\": app_name,\n                \"finding_type\": \"UNUSED_APPROVED_SCOPES\",\n                \"severity\": \"LOW\",\n                \"detail\": f\"{len(unused)} approved scopes not currently granted\",\n                \"unused_scopes\": list(unused)\n            })\n\n        # Check for overly broad permissions\n        broad_patterns = [\n            (\"Mail.ReadWrite\", \"Mail.Read\", \"Write access to mail when only read needed\"),\n            (\"Files.ReadWrite.All\", \"Files.Read.All\", \"Write access to all files when only read needed\"),\n            (\"Directory.ReadWrite.All\", \"Directory.Read.All\", \"Write access to directory when only read needed\"),\n            (\"User.ReadWrite.All\", \"User.Read.All\", \"Write access to users when only read needed\"),\n        ]\n\n        for broad, narrow, description in broad_patterns:\n            if broad in actual_scopes:\n                findings.append({\n                    \"app_name\": app_name,\n                    \"finding_type\": \"OVERLY_BROAD_SCOPE\",\n                    \"severity\": \"MEDIUM\",\n                    \"detail\": description,\n                    \"current_scope\": broad,\n                    \"recommended_scope\": narrow,\n                    \"recommendation\": f\"Downgrade from {broad} to {narrow}\"\n                })\n\n    return findings\n```\n\n### Step 4: Audit Token Usage and Detect Stale Grants\n\nIdentify OAuth tokens that are no longer actively used:\n\n```python\n\"\"\"\nToken Usage Audit\nAnalyzes sign-in logs and API activity to identify stale OAuth grants.\n\"\"\"\n\ndef audit_token_usage(auditor, days_inactive=90):\n    \"\"\"Identify OAuth grants with no recent API activity.\"\"\"\n    # Get sign-in activity for service principals\n    url = f\"{auditor.base_url}\u002FauditLogs\u002FsignIns\"\n    params = {\n        \"$filter\": f\"createdDateTime ge {(datetime.utcnow() - timedelta(days=days_inactive)).isoformat()}Z and signInEventTypes\u002Fany(t: t eq 'servicePrincipal')\",\n        \"$top\": 999\n    }\n\n    active_apps = set()\n    while url:\n        response = requests.get(url, headers=auditor.headers, params=params)\n        data = response.json()\n        for signin in data.get(\"value\", []):\n            active_apps.add(signin.get(\"appId\"))\n        url = data.get(\"@odata.nextLink\")\n        params = {}\n\n    # Compare against all granted apps\n    all_grants = auditor.get_oauth2_permission_grants()\n    sp_map = {sp[\"id\"]: sp for sp in auditor.get_all_service_principals()}\n\n    stale_grants = []\n    for grant in all_grants:\n        sp = sp_map.get(grant[\"clientId\"], {})\n        app_id = sp.get(\"appId\")\n\n        if app_id and app_id not in active_apps:\n            stale_grants.append({\n                \"app_name\": sp.get(\"displayName\", \"Unknown\"),\n                \"app_id\": app_id,\n                \"scopes\": grant.get(\"scope\", \"\").split(),\n                \"consent_type\": grant.get(\"consentType\"),\n                \"is_third_party\": sp.get(\"appOwnerOrganizationId\") != auditor.tenant_id,\n                \"days_inactive\": days_inactive,\n                \"recommendation\": \"Revoke - no API activity in {days_inactive} days\"\n            })\n\n    return sorted(stale_grants, key=lambda x: len(x[\"scopes\"]), reverse=True)\n```\n\n### Step 5: Generate Remediation Plan and Execute Scope Reduction\n\nCreate and execute the scope minimization remediation plan:\n\n```python\n\"\"\"\nOAuth Scope Remediation\nGenerates and executes scope reduction actions.\n\"\"\"\n\ndef generate_remediation_plan(findings, stale_grants):\n    \"\"\"Create prioritized remediation plan.\"\"\"\n    plan = []\n\n    # Priority 1: Revoke unapproved applications\n    for f in findings:\n        if f[\"finding_type\"] == \"UNAPPROVED_APPLICATION\":\n            plan.append({\n                \"priority\": 1,\n                \"action\": \"REVOKE_ALL_PERMISSIONS\",\n                \"app_name\": f[\"app_name\"],\n                \"reason\": \"Unapproved third-party application\",\n                \"impact\": f\"Removes {len(f['scopes'])} permission grants\",\n                \"risk_if_not_addressed\": \"CRITICAL\"\n            })\n\n    # Priority 2: Remove excessive scopes from approved apps\n    for f in findings:\n        if f[\"finding_type\"] == \"EXCESSIVE_SCOPES\":\n            plan.append({\n                \"priority\": 2,\n                \"action\": \"REMOVE_EXCESSIVE_SCOPES\",\n                \"app_name\": f[\"app_name\"],\n                \"scopes_to_remove\": f[\"excessive_scopes\"],\n                \"reason\": \"Scopes beyond approved catalog\",\n                \"risk_if_not_addressed\": f[\"severity\"]\n            })\n\n    # Priority 3: Downgrade overly broad scopes\n    for f in findings:\n        if f[\"finding_type\"] == \"OVERLY_BROAD_SCOPE\":\n            plan.append({\n                \"priority\": 3,\n                \"action\": \"DOWNGRADE_SCOPE\",\n                \"app_name\": f[\"app_name\"],\n                \"current_scope\": f[\"current_scope\"],\n                \"target_scope\": f[\"recommended_scope\"],\n                \"reason\": f[\"detail\"],\n                \"risk_if_not_addressed\": \"MEDIUM\"\n            })\n\n    # Priority 4: Revoke stale grants\n    for grant in stale_grants:\n        plan.append({\n            \"priority\": 4,\n            \"action\": \"REVOKE_STALE_GRANT\",\n            \"app_name\": grant[\"app_name\"],\n            \"scopes_to_revoke\": grant[\"scopes\"],\n            \"reason\": f\"No API activity in {grant['days_inactive']} days\",\n            \"risk_if_not_addressed\": \"MEDIUM\"\n        })\n\n    return sorted(plan, key=lambda x: x[\"priority\"])\n\ndef execute_scope_reduction(auditor, grant_id, scopes_to_remove):\n    \"\"\"Remove specific scopes from an OAuth permission grant.\"\"\"\n    # Get current grant\n    url = f\"{auditor.base_url}\u002Foauth2PermissionGrants\u002F{grant_id}\"\n    response = requests.get(url, headers=auditor.headers)\n    current_grant = response.json()\n\n    current_scopes = set(current_grant.get(\"scope\", \"\").split())\n    updated_scopes = current_scopes - set(scopes_to_remove)\n\n    if not updated_scopes:\n        # Remove entire grant\n        requests.delete(url, headers=auditor.headers)\n        return {\"action\": \"grant_deleted\", \"grant_id\": grant_id}\n    else:\n        # Update with reduced scopes\n        update_body = {\"scope\": \" \".join(updated_scopes)}\n        requests.patch(url, headers=auditor.headers, json=update_body)\n        return {\n            \"action\": \"scopes_reduced\",\n            \"grant_id\": grant_id,\n            \"removed\": list(scopes_to_remove),\n            \"remaining\": list(updated_scopes)\n        }\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **OAuth Scope** | Permission string defining the specific API access level granted to a client application (e.g., Mail.Read, Files.ReadWrite.All) |\n| **Delegated Permission** | OAuth scope exercised on behalf of a signed-in user, limited by both the app's permissions and the user's own access rights |\n| **Application Permission** | OAuth scope granted directly to the application without user context, providing access to all users' data (high risk) |\n| **Admin Consent** | Tenant-wide permission grant made by an administrator that applies to all users without individual consent |\n| **Scope Minimization** | Security principle of reducing OAuth permissions to the minimum set required for application functionality |\n| **Stale Grant** | OAuth permission that remains active but has no recent API usage, indicating the integration is abandoned or deprecated |\n\n## Tools & Systems\n\n- **Microsoft Entra Admin Center**: Portal for reviewing enterprise applications, consent permissions, and OAuth grant management\n- **Nudge Security**: SaaS security platform for discovering OAuth grants, assessing third-party risk, and automating scope reviews\n- **Cerby**: Non-SSO application management platform for auditing OAuth integrations and managing shared accounts\n- **Microsoft Graph API**: Programmatic interface for enumerating and modifying OAuth permission grants at scale\n\n## Common Scenarios\n\n### Scenario: Post-Breach OAuth Scope Audit\n\n**Context**: After a phishing attack compromised an admin account, investigation reveals the attacker registered a malicious OAuth application with Mail.ReadWrite and Files.ReadWrite.All scopes, exfiltrating 6 months of email. The organization needs a comprehensive OAuth scope review.\n\n**Approach**:\n1. Immediately revoke all OAuth grants from the compromised admin session\n2. Enumerate all service principals and permission grants across the tenant\n3. Flag all applications registered in the last 90 days for manual review\n4. Classify all third-party application scopes using the risk framework\n5. Identify applications with critical scopes (Mail.ReadWrite, Files.ReadWrite.All, Directory.ReadWrite.All)\n6. Cross-reference against approved application catalog from IT procurement\n7. Revoke all unapproved applications immediately\n8. Downgrade over-permissioned approved applications to minimum required scopes\n9. Implement admin consent workflow to prevent future uncontrolled OAuth grants\n10. Enable consent policy requiring admin approval for high-risk scopes\n\n**Pitfalls**:\n- Revoking permissions for business-critical integrations without coordination causes service disruption\n- Not checking for application-level permissions (vs delegated) which are higher risk and often overlooked\n- Missing multi-tenant applications where the publisher tenant differs from the consuming tenant\n- Not implementing ongoing monitoring to detect new unauthorized OAuth grants after remediation\n\n## Output Format\n\n```\nOAUTH SCOPE MINIMIZATION REVIEW REPORT\n=========================================\nTenant:              corp.onmicrosoft.com\nReview Period:       2026-02-01 to 2026-02-24\nTotal Applications:  147\nThird-Party Apps:    98\nFirst-Party Apps:    49\n\nPERMISSION INVENTORY\nTotal OAuth Grants:          487\n  Delegated Permissions:     312\n  Application Permissions:   175\n  Admin-Consented:           89\n  User-Consented:            223\n\nRISK CLASSIFICATION\nCritical Risk Apps:     7\n  - UnknownCRMApp (Mail.ReadWrite, Files.ReadWrite.All - UNAPPROVED)\n  - LegacySync (Directory.ReadWrite.All - EXCESSIVE)\n  - DevToolX (Application.ReadWrite.All - OVERLY BROAD)\nHigh Risk Apps:         18\nMedium Risk Apps:       34\nLow Risk Apps:          88\n\nFINDINGS\nUnapproved Applications:        12 (REVOKE IMMEDIATELY)\nExcessive Scopes:               23 apps with scopes beyond approved list\nOverly Broad Permissions:       15 apps that can be downgraded\nStale Grants (90+ days):        31 apps with no recent API activity\n\nREMEDIATION PLAN\nPriority 1 (Immediate):    12 unapproved app revocations\nPriority 2 (This Week):    23 excessive scope removals\nPriority 3 (This Month):   15 scope downgrades\nPriority 4 (Next Quarter): 31 stale grant revocations\n\nEstimated Scope Reduction:  34% of total permissions\n```\n","# Performing OAuth Scope Minimization Review\n\n## When to Use\n\n- Annual or quarterly review of third-party application OAuth permissions\n- After a security incident involving compromised OAuth tokens or unauthorized data access\n- Compliance audit requiring documentation of third-party data access (GDPR Article 28, SOC 2)\n- Discovery of shadow IT applications accessing organizational data via OAuth grants\n- Migration or consolidation of SaaS applications requiring permission cleanup\n- Implementing least-privilege principle for API integrations\n\n**Do not use** for reviewing first-party application permissions within the same trust boundary; OAuth scope minimization focuses on third-party and cross-boundary consent grants.\n\n## Prerequisites\n\n- Admin access to identity providers (Microsoft Entra ID, Okta, Google Workspace)\n- Microsoft Graph API permissions: Application.Read.All, OAuth2PermissionGrant.ReadWrite.All\n- Inventory of approved third-party integrations from procurement or IT governance\n- OAuth scope risk classification framework\n- Tools for token analysis (jwt.io for manual review, automated scripts for bulk analysis)\n\n## Workflow\n\n### Step 1: Inventory All OAuth Grants and Consent Permissions\n\nEnumerate all OAuth application registrations and delegated permissions:\n\n```python\n\"\"\"\nOAuth Grant Inventory - Microsoft Entra ID\nEnumerates all application registrations, service principals,\nand delegated\u002Fapplication permission grants.\n\"\"\"\nimport requests\nimport json\nfrom collections import defaultdict\n\nclass EntraOAuthAuditor:\n    def __init__(self, tenant_id, client_id, client_secret):\n        self.tenant_id = tenant_id\n        self.base_url = \"https:\u002F\u002Fgraph.microsoft.com\u002Fv1.0\"\n        self.token = self._get_token(client_id, client_secret)\n        self.headers = {\"Authorization\": f\"Bearer {self.token}\"}\n\n    def _get_token(self, client_id, client_secret):\n        url = f\"https:\u002F\u002Flogin.microsoftonline.com\u002F{self.tenant_id}\u002Foauth2\u002Fv2.0\u002Ftoken\"\n        response = requests.post(url, data={\n            \"grant_type\": \"client_credentials\",\n            \"client_id\": client_id,\n            \"client_secret\": client_secret,\n            \"scope\": \"https:\u002F\u002Fgraph.microsoft.com\u002F.default\"\n        })\n        return response.json()[\"access_token\"]\n\n    def get_all_service_principals(self):\n        \"\"\"Get all service principals (enterprise applications).\"\"\"\n        apps = []\n        url = f\"{self.base_url}\u002FservicePrincipals?$top=999&$select=id,appId,displayName,appOwnerOrganizationId,servicePrincipalType,accountEnabled,createdDateTime\"\n\n        while url:\n            response = requests.get(url, headers=self.headers)\n            data = response.json()\n            apps.extend(data.get(\"value\", []))\n            url = data.get(\"@odata.nextLink\")\n\n        return apps\n\n    def get_oauth2_permission_grants(self):\n        \"\"\"Get all delegated permission grants (user consent).\"\"\"\n        grants = []\n        url = f\"{self.base_url}\u002Foauth2PermissionGrants?$top=999\"\n\n        while url:\n            response = requests.get(url, headers=self.headers)\n            data = response.json()\n            grants.extend(data.get(\"value\", []))\n            url = data.get(\"@odata.nextLink\")\n\n        return grants\n\n    def get_app_role_assignments(self, sp_id):\n        \"\"\"Get application permission assignments for a service principal.\"\"\"\n        url = f\"{self.base_url}\u002FservicePrincipals\u002F{sp_id}\u002FappRoleAssignments\"\n        response = requests.get(url, headers=self.headers)\n        return response.json().get(\"value\", [])\n\n    def build_permission_inventory(self):\n        \"\"\"Build comprehensive OAuth permission inventory.\"\"\"\n        service_principals = self.get_all_service_principals()\n        delegated_grants = self.get_oauth2_permission_grants()\n\n        # Map service principal IDs to names\n        sp_map = {sp[\"id\"]: sp for sp in service_principals}\n\n        inventory = []\n\n        # Process delegated permissions\n        for grant in delegated_grants:\n            sp = sp_map.get(grant[\"clientId\"], {})\n            scopes = grant.get(\"scope\", \"\").split()\n\n            for scope in scopes:\n                if not scope:\n                    continue\n                inventory.append({\n                    \"app_name\": sp.get(\"displayName\", \"Unknown\"),\n                    \"app_id\": grant.get(\"clientId\"),\n                    \"publisher_tenant\": sp.get(\"appOwnerOrganizationId\"),\n                    \"is_third_party\": sp.get(\"appOwnerOrganizationId\") != self.tenant_id,\n                    \"permission_type\": \"Delegated\",\n                    \"scope\": scope,\n                    \"consent_type\": grant.get(\"consentType\"),  # AllPrincipals or Principal\n                    \"principal_id\": grant.get(\"principalId\"),\n                    \"granted_date\": sp.get(\"createdDateTime\"),\n                    \"is_enabled\": sp.get(\"accountEnabled\", True)\n                })\n\n        # Process application permissions\n        for sp in service_principals:\n            app_roles = self.get_app_role_assignments(sp[\"id\"])\n            for role in app_roles:\n                inventory.append({\n                    \"app_name\": sp.get(\"displayName\"),\n                    \"app_id\": sp.get(\"id\"),\n                    \"publisher_tenant\": sp.get(\"appOwnerOrganizationId\"),\n                    \"is_third_party\": sp.get(\"appOwnerOrganizationId\") != self.tenant_id,\n                    \"permission_type\": \"Application\",\n                    \"scope\": role.get(\"appRoleId\"),\n                    \"consent_type\": \"AdminConsent\",\n                    \"granted_date\": role.get(\"createdDateTime\"),\n                    \"is_enabled\": sp.get(\"accountEnabled\", True)\n                })\n\n        return inventory\n```\n\n### Step 2: Classify OAuth Scopes by Risk Level\n\nCategorize permissions based on data access sensitivity:\n\n```python\n\"\"\"\nOAuth Scope Risk Classification\nMaps API scopes to risk levels based on data sensitivity and access breadth.\n\"\"\"\n\nMICROSOFT_GRAPH_SCOPE_RISK = {\n    # CRITICAL - Full administrative or unrestricted access\n    \"critical\": {\n        \"scopes\": [\n            \"Directory.ReadWrite.All\",\n            \"RoleManagement.ReadWrite.Directory\",\n            \"Application.ReadWrite.All\",\n            \"AppRoleAssignment.ReadWrite.All\",\n            \"Mail.ReadWrite\",\n            \"Mail.Send\",\n            \"Files.ReadWrite.All\",\n            \"Sites.FullControl.All\",\n            \"User.ReadWrite.All\",\n            \"Group.ReadWrite.All\",\n            \"MailboxSettings.ReadWrite\",\n            \"full_access_as_app\",\n        ],\n        \"risk_description\": \"Can read\u002Fwrite all data, modify directory, or impersonate users\",\n        \"review_frequency\": \"Monthly\",\n        \"requires_admin_consent\": True\n    },\n    # HIGH - Broad read access or sensitive data write\n    \"high\": {\n        \"scopes\": [\n            \"Mail.Read\",\n            \"Mail.Read.Shared\",\n            \"Calendars.ReadWrite\",\n            \"Contacts.ReadWrite\",\n            \"Files.Read.All\",\n            \"Sites.Read.All\",\n            \"User.Read.All\",\n            \"Group.Read.All\",\n            \"Directory.Read.All\",\n            \"AuditLog.Read.All\",\n            \"SecurityEvents.ReadWrite.All\",\n            \"TeamSettings.ReadWrite.All\",\n        ],\n        \"risk_description\": \"Broad read access to sensitive organizational data\",\n        \"review_frequency\": \"Quarterly\",\n        \"requires_admin_consent\": True\n    },\n    # MEDIUM - Scoped data access\n    \"medium\": {\n        \"scopes\": [\n            \"Calendars.Read\",\n            \"Contacts.Read\",\n            \"Files.ReadWrite\",\n            \"Sites.ReadWrite.All\",\n            \"Tasks.ReadWrite\",\n            \"Notes.ReadWrite.All\",\n            \"Chat.ReadWrite\",\n            \"ChannelMessage.Send\",\n            \"Team.ReadBasic.All\",\n        ],\n        \"risk_description\": \"Scoped access to specific data types with write capability\",\n        \"review_frequency\": \"Semi-annually\"\n    },\n    # LOW - Minimal or user-profile only access\n    \"low\": {\n        \"scopes\": [\n            \"User.Read\",\n            \"openid\",\n            \"profile\",\n            \"email\",\n            \"offline_access\",\n            \"Calendars.Read.Shared\",\n            \"People.Read\",\n            \"User.ReadBasic.All\",\n        ],\n        \"risk_description\": \"Basic user profile or minimal scoped access\",\n        \"review_frequency\": \"Annually\"\n    }\n}\n\ndef classify_scope_risk(scope):\n    \"\"\"Classify a single OAuth scope by risk level.\"\"\"\n    for risk_level, config in MICROSOFT_GRAPH_SCOPE_RISK.items():\n        if scope in config[\"scopes\"]:\n            return {\n                \"scope\": scope,\n                \"risk_level\": risk_level,\n                \"description\": config[\"risk_description\"],\n                \"review_frequency\": config[\"review_frequency\"]\n            }\n    # Unknown scopes default to HIGH risk\n    return {\n        \"scope\": scope,\n        \"risk_level\": \"high\",\n        \"description\": \"Unknown scope - requires manual classification\",\n        \"review_frequency\": \"Quarterly\"\n    }\n\ndef analyze_app_risk(app_permissions):\n    \"\"\"Calculate aggregate risk score for an application's permissions.\"\"\"\n    risk_weights = {\"critical\": 40, \"high\": 20, \"medium\": 10, \"low\": 2}\n    total_score = 0\n    classified_scopes = []\n\n    for perm in app_permissions:\n        classification = classify_scope_risk(perm[\"scope\"])\n        classified_scopes.append(classification)\n        total_score += risk_weights.get(classification[\"risk_level\"], 10)\n\n    # Bonus risk for application (vs delegated) permissions\n    app_type_permissions = [p for p in app_permissions if p[\"permission_type\"] == \"Application\"]\n    total_score += len(app_type_permissions) * 15\n\n    # Bonus risk for admin-consented broad access\n    admin_consent = [p for p in app_permissions if p[\"consent_type\"] == \"AllPrincipals\"]\n    total_score += len(admin_consent) * 10\n\n    if total_score >= 100:\n        aggregate_risk = \"CRITICAL\"\n    elif total_score >= 60:\n        aggregate_risk = \"HIGH\"\n    elif total_score >= 30:\n        aggregate_risk = \"MEDIUM\"\n    else:\n        aggregate_risk = \"LOW\"\n\n    return {\n        \"total_score\": total_score,\n        \"aggregate_risk\": aggregate_risk,\n        \"scope_count\": len(app_permissions),\n        \"critical_scopes\": len([s for s in classified_scopes if s[\"risk_level\"] == \"critical\"]),\n        \"high_scopes\": len([s for s in classified_scopes if s[\"risk_level\"] == \"high\"]),\n        \"classified_scopes\": classified_scopes\n    }\n```\n\n### Step 3: Identify Over-Permissioned Applications\n\nDetect apps requesting more permissions than functionally needed:\n\n```python\n\"\"\"\nOver-Permission Detection\nIdentifies applications with excessive OAuth scopes relative to their function.\n\"\"\"\n\ndef detect_over_permissions(inventory, approved_apps_catalog):\n    \"\"\"\n    Compare actual permissions against approved scope catalog\n    to find over-permissioned applications.\n    \"\"\"\n    findings = []\n\n    # Group permissions by application\n    app_permissions = defaultdict(list)\n    for perm in inventory:\n        app_permissions[perm[\"app_name\"]].append(perm)\n\n    for app_name, permissions in app_permissions.items():\n        # Check against approved catalog\n        approved = approved_apps_catalog.get(app_name)\n\n        if not approved:\n            # Unknown\u002Funapproved application\n            findings.append({\n                \"app_name\": app_name,\n                \"finding_type\": \"UNAPPROVED_APPLICATION\",\n                \"severity\": \"HIGH\",\n                \"detail\": f\"Application not in approved catalog with {len(permissions)} permission grants\",\n                \"scopes\": [p[\"scope\"] for p in permissions],\n                \"recommendation\": \"Review and approve or revoke all permissions\"\n            })\n            continue\n\n        approved_scopes = set(approved.get(\"approved_scopes\", []))\n        actual_scopes = set(p[\"scope\"] for p in permissions)\n\n        # Find excessive scopes (granted but not approved)\n        excessive = actual_scopes - approved_scopes\n        if excessive:\n            risk = analyze_app_risk([p for p in permissions if p[\"scope\"] in excessive])\n            findings.append({\n                \"app_name\": app_name,\n                \"finding_type\": \"EXCESSIVE_SCOPES\",\n                \"severity\": risk[\"aggregate_risk\"],\n                \"detail\": f\"{len(excessive)} scopes beyond approved list\",\n                \"excessive_scopes\": list(excessive),\n                \"approved_scopes\": list(approved_scopes),\n                \"recommendation\": \"Remove excessive scopes or update approved catalog\"\n            })\n\n        # Find unused scopes (approved but activity logs show no API calls)\n        # This requires API activity log correlation\n        unused = approved_scopes - actual_scopes\n        if unused:\n            findings.append({\n                \"app_name\": app_name,\n                \"finding_type\": \"UNUSED_APPROVED_SCOPES\",\n                \"severity\": \"LOW\",\n                \"detail\": f\"{len(unused)} approved scopes not currently granted\",\n                \"unused_scopes\": list(unused)\n            })\n\n        # Check for overly broad permissions\n        broad_patterns = [\n            (\"Mail.ReadWrite\", \"Mail.Read\", \"Write access to mail when only read needed\"),\n            (\"Files.ReadWrite.All\", \"Files.Read.All\", \"Write access to all files when only read needed\"),\n            (\"Directory.ReadWrite.All\", \"Directory.Read.All\", \"Write access to directory when only read needed\"),\n            (\"User.ReadWrite.All\", \"User.Read.All\", \"Write access to users when only read needed\"),\n        ]\n\n        for broad, narrow, description in broad_patterns:\n            if broad in actual_scopes:\n                findings.append({\n                    \"app_name\": app_name,\n                    \"finding_type\": \"OVERLY_BROAD_SCOPE\",\n                    \"severity\": \"MEDIUM\",\n                    \"detail\": description,\n                    \"current_scope\": broad,\n                    \"recommended_scope\": narrow,\n                    \"recommendation\": f\"Downgrade from {broad} to {narrow}\"\n                })\n\n    return findings\n```\n\n### Step 4: Audit Token Usage and Detect Stale Grants\n\nIdentify OAuth tokens that are no longer actively used:\n\n```python\n\"\"\"\nToken Usage Audit\nAnalyzes sign-in logs and API activity to identify stale OAuth grants.\n\"\"\"\n\ndef audit_token_usage(auditor, days_inactive=90):\n    \"\"\"Identify OAuth grants with no recent API activity.\"\"\"\n    # Get sign-in activity for service principals\n    url = f\"{auditor.base_url}\u002FauditLogs\u002FsignIns\"\n    params = {\n        \"$filter\": f\"createdDateTime ge {(datetime.utcnow() - timedelta(days=days_inactive)).isoformat()}Z and signInEventTypes\u002Fany(t: t eq 'servicePrincipal')\",\n        \"$top\": 999\n    }\n\n    active_apps = set()\n    while url:\n        response = requests.get(url, headers=auditor.headers, params=params)\n        data = response.json()\n        for signin in data.get(\"value\", []):\n            active_apps.add(signin.get(\"appId\"))\n        url = data.get(\"@odata.nextLink\")\n        params = {}\n\n    # Compare against all granted apps\n    all_grants = auditor.get_oauth2_permission_grants()\n    sp_map = {sp[\"id\"]: sp for sp in auditor.get_all_service_principals()}\n\n    stale_grants = []\n    for grant in all_grants:\n        sp = sp_map.get(grant[\"clientId\"], {})\n        app_id = sp.get(\"appId\")\n\n        if app_id and app_id not in active_apps:\n            stale_grants.append({\n                \"app_name\": sp.get(\"displayName\", \"Unknown\"),\n                \"app_id\": app_id,\n                \"scopes\": grant.get(\"scope\", \"\").split(),\n                \"consent_type\": grant.get(\"consentType\"),\n                \"is_third_party\": sp.get(\"appOwnerOrganizationId\") != auditor.tenant_id,\n                \"days_inactive\": days_inactive,\n                \"recommendation\": \"Revoke - no API activity in {days_inactive} days\"\n            })\n\n    return sorted(stale_grants, key=lambda x: len(x[\"scopes\"]), reverse=True)\n```\n\n### Step 5: Generate Remediation Plan and Execute Scope Reduction\n\nCreate and execute the scope minimization remediation plan:\n\n```python\n\"\"\"\nOAuth Scope Remediation\nGenerates and executes scope reduction actions.\n\"\"\"\n\ndef generate_remediation_plan(findings, stale_grants):\n    \"\"\"Create prioritized remediation plan.\"\"\"\n    plan = []\n\n    # Priority 1: Revoke unapproved applications\n    for f in findings:\n        if f[\"finding_type\"] == \"UNAPPROVED_APPLICATION\":\n            plan.append({\n                \"priority\": 1,\n                \"action\": \"REVOKE_ALL_PERMISSIONS\",\n                \"app_name\": f[\"app_name\"],\n                \"reason\": \"Unapproved third-party application\",\n                \"impact\": f\"Removes {len(f['scopes'])} permission grants\",\n                \"risk_if_not_addressed\": \"CRITICAL\"\n            })\n\n    # Priority 2: Remove excessive scopes from approved apps\n    for f in findings:\n        if f[\"finding_type\"] == \"EXCESSIVE_SCOPES\":\n            plan.append({\n                \"priority\": 2,\n                \"action\": \"REMOVE_EXCESSIVE_SCOPES\",\n                \"app_name\": f[\"app_name\"],\n                \"scopes_to_remove\": f[\"excessive_scopes\"],\n                \"reason\": \"Scopes beyond approved catalog\",\n                \"risk_if_not_addressed\": f[\"severity\"]\n            })\n\n    # Priority 3: Downgrade overly broad scopes\n    for f in findings:\n        if f[\"finding_type\"] == \"OVERLY_BROAD_SCOPE\":\n            plan.append({\n                \"priority\": 3,\n                \"action\": \"DOWNGRADE_SCOPE\",\n                \"app_name\": f[\"app_name\"],\n                \"current_scope\": f[\"current_scope\"],\n                \"target_scope\": f[\"recommended_scope\"],\n                \"reason\": f[\"detail\"],\n                \"risk_if_not_addressed\": \"MEDIUM\"\n            })\n\n    # Priority 4: Revoke stale grants\n    for grant in stale_grants:\n        plan.append({\n            \"priority\": 4,\n            \"action\": \"REVOKE_STALE_GRANT\",\n            \"app_name\": grant[\"app_name\"],\n            \"scopes_to_revoke\": grant[\"scopes\"],\n            \"reason\": f\"No API activity in {grant['days_inactive']} days\",\n            \"risk_if_not_addressed\": \"MEDIUM\"\n        })\n\n    return sorted(plan, key=lambda x: x[\"priority\"])\n\ndef execute_scope_reduction(auditor, grant_id, scopes_to_remove):\n    \"\"\"Remove specific scopes from an OAuth permission grant.\"\"\"\n    # Get current grant\n    url = f\"{auditor.base_url}\u002Foauth2PermissionGrants\u002F{grant_id}\"\n    response = requests.get(url, headers=auditor.headers)\n    current_grant = response.json()\n\n    current_scopes = set(current_grant.get(\"scope\", \"\").split())\n    updated_scopes = current_scopes - set(scopes_to_remove)\n\n    if not updated_scopes:\n        # Remove entire grant\n        requests.delete(url, headers=auditor.headers)\n        return {\"action\": \"grant_deleted\", \"grant_id\": grant_id}\n    else:\n        # Update with reduced scopes\n        update_body = {\"scope\": \" \".join(updated_scopes)}\n        requests.patch(url, headers=auditor.headers, json=update_body)\n        return {\n            \"action\": \"scopes_reduced\",\n            \"grant_id\": grant_id,\n            \"removed\": list(scopes_to_remove),\n            \"remaining\": list(updated_scopes)\n        }\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **OAuth Scope** | Permission string defining the specific API access level granted to a client application (e.g., Mail.Read, Files.ReadWrite.All) |\n| **Delegated Permission** | OAuth scope exercised on behalf of a signed-in user, limited by both the app's permissions and the user's own access rights |\n| **Application Permission** | OAuth scope granted directly to the application without user context, providing access to all users' data (high risk) |\n| **Admin Consent** | Tenant-wide permission grant made by an administrator that applies to all users without individual consent |\n| **Scope Minimization** | Security principle of reducing OAuth permissions to the minimum set required for application functionality |\n| **Stale Grant** | OAuth permission that remains active but has no recent API usage, indicating the integration is abandoned or deprecated |\n\n## Tools & Systems\n\n- **Microsoft Entra Admin Center**: Portal for reviewing enterprise applications, consent permissions, and OAuth grant management\n- **Nudge Security**: SaaS security platform for discovering OAuth grants, assessing third-party risk, and automating scope reviews\n- **Cerby**: Non-SSO application management platform for auditing OAuth integrations and managing shared accounts\n- **Microsoft Graph API**: Programmatic interface for enumerating and modifying OAuth permission grants at scale\n\n## Common Scenarios\n\n### Scenario: Post-Breach OAuth Scope Audit\n\n**Context**: After a phishing attack compromised an admin account, investigation reveals the attacker registered a malicious OAuth application with Mail.ReadWrite and Files.ReadWrite.All scopes, exfiltrating 6 months of email. The organization needs a comprehensive OAuth scope review.\n\n**Approach**:\n1. Immediately revoke all OAuth grants from the compromised admin session\n2. Enumerate all service principals and permission grants across the tenant\n3. Flag all applications registered in the last 90 days for manual review\n4. Classify all third-party application scopes using the risk framework\n5. Identify applications with critical scopes (Mail.ReadWrite, Files.ReadWrite.All, Directory.ReadWrite.All)\n6. Cross-reference against approved application catalog from IT procurement\n7. Revoke all unapproved applications immediately\n8. Downgrade over-permissioned approved applications to minimum required scopes\n9. Implement admin consent workflow to prevent future uncontrolled OAuth grants\n10. Enable consent policy requiring admin approval for high-risk scopes\n\n**Pitfalls**:\n- Revoking permissions for business-critical integrations without coordination causes service disruption\n- Not checking for application-level permissions (vs delegated) which are higher risk and often overlooked\n- Missing multi-tenant applications where the publisher tenant differs from the consuming tenant\n- Not implementing ongoing monitoring to detect new unauthorized OAuth grants after remediation\n\n## Output Format\n\n```\nOAUTH SCOPE MINIMIZATION REVIEW REPORT\n=========================================\nTenant:              corp.onmicrosoft.com\nReview Period:       2026-02-01 to 2026-02-24\nTotal Applications:  147\nThird-Party Apps:    98\nFirst-Party Apps:    49\n\nPERMISSION INVENTORY\nTotal OAuth Grants:          487\n  Delegated Permissions:     312\n  Application Permissions:   175\n  Admin-Consented:           89\n  User-Consented:            223\n\nRISK CLASSIFICATION\nCritical Risk Apps:     7\n  - UnknownCRMApp (Mail.ReadWrite, Files.ReadWrite.All - UNAPPROVED)\n  - LegacySync (Directory.ReadWrite.All - EXCESSIVE)\n  - DevToolX (Application.ReadWrite.All - OVERLY BROAD)\nHigh Risk Apps:         18\nMedium Risk Apps:       34\nLow Risk Apps:          88\n\nFINDINGS\nUnapproved Applications:        12 (REVOKE IMMEDIATELY)\nExcessive Scopes:               23 apps with scopes beyond approved list\nOverly Broad Permissions:       15 apps that can be downgraded\nStale Grants (90+ days):        31 apps with no recent API activity\n\nREMEDIATION PLAN\nPriority 1 (Immediate):    12 unapproved app revocations\nPriority 2 (This Week):    23 excessive scope removals\nPriority 3 (This Month):   15 scope downgrades\nPriority 4 (Next Quarter): 31 stale grant revocations\n\nEstimated Scope Reduction:  34% of total permissions\n```\n",{"name":5,"tags":43,"author":48,"domain":35,"license":14,"version":49,"subdomain":50,"description":51},[22,44,45,46,26,47],"scope-minimization","API-security","consent-review","token-audit","mahipal","1.0","identity-access-management","Performs OAuth 2.0 scope minimization review to identify over-permissioned third-party application integrations, excessive API scopes, unused token grants, and risky OAuth consent patterns across identity providers and SaaS platforms. Activates for requests involving OAuth scope audit, API permission review, third-party app risk assessment, or consent grant minimization.\n","master","3f5d983eb4ef375b749adcd6b07ec03bd82ae8a8","_universal\u002Fcybersecurity-skills\u002Fskills\u002Fperforming-oauth-scope-minimization-review",0,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills","https:\u002F\u002Fgithub.com\u002Fmicsapp","2026-03-20 11:24:18",{"source":8,"skillName":5,"commands":60,"prompt":70,"zipAvailable":71},[61,64,67],{"tool":62,"command":63},"npx","npx skills add micsapp\u002Fmicstec-skills --skill performing-oauth-scope-minimization-review",{"tool":65,"command":66},"bunx","bunx skills add micsapp\u002Fmicstec-skills --skill performing-oauth-scope-minimization-review",{"tool":68,"command":69},"pnpm","pnpm dlx skills add micsapp\u002Fmicstec-skills --skill performing-oauth-scope-minimization-review","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fperforming-oauth-scope-minimization-review\u002FSKILL.md",true,[73,78,84],{"path":74,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fperforming-oauth-scope-minimization-review\u002FLICENSE",{"path":79,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fapi-reference.md","REFERENCE","参考文档",1968,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fperforming-oauth-scope-minimization-review\u002Freferences\u002Fapi-reference.md",{"path":85,"resourceType":86,"resourceTypeDesc":87,"sizeBytes":88,"sourceHtmlUrl":89},"scripts\u002Fagent.py","SCRIPT","脚本",7387,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fperforming-oauth-scope-minimization-review\u002Fscripts\u002Fagent.py",[91,118,140,158,175,199],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":38},"01M6HBTJ02FXBFG9NYEHHYAP52","azure-apim-architecture","Analyzes and explains Azure API Management architecture decisions for enterprise API marketplace implementations using VNet Internal mode, Front Door, hybrid authentication, and multi-environment strategies. Use when discussing APIM component selection, network topology, cost optimization, or comparing alternatives like workspaces vs instances, VNet Internal vs External mode, or Front Door vs Application Gateway.","MIT","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fazure-apim-architecture\u002FSKILL.md",[],[99,100,101,102,103,104,105,106,107,27,108,109,110,111,112,113,114,115,116,117],"architecture","azure","azure apim architecture","component","authentication","gateway","topology","Optimization","network","team","environment","multi-environment","workspaces","instances","selection","strategies","azure api management","mode","for",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":38},"01M6HBT7J4H082JEEA670B3EQ9","apiops-deployment","Guides deployment of Azure API Management infrastructure using Infrastructure as Code (Bicep\u002FTerraform), CI\u002FCD pipelines (GitHub Actions\u002FAzure DevOps), and APIOps workflows. Use when deploying APIM, creating pipelines, or implementing dev→test→prod promotion strategies.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapiops-deployment\u002FSKILL.md",[],[125,126,127,128,100,129,130,131,132,133,134,135,27,108,114,136,137,115,138,139],"deployment","apiops deployment","workflows","azure devops","infrastructure","code","infrastructure as code","actions","ci","github actions","github-actions","as","guides","CI\u002FCD","implementing",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":38},"01M6HBT2HEA23THNE9E00GYQBE","apim-policy-authoring","Creates production-ready Azure API Management policy XML for authentication (OAuth 2.0, JWT validation, subscription keys), rate limiting, CORS configuration, error handling, and API transformations. Use when implementing API security, access control, or request\u002Fresponse processing logic.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapim-policy-authoring\u002FSKILL.md",[],[147,148,149,37,100,103,27,108,29,150,151,152,153,154,155,115,156,157,139,117],"policy","authoring","apim policy authoring","use","ready","api security","Access Control","error","processing","cors configuration","production-ready",{"skillNo":159,"name":160,"nameZh":6,"description":161,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":162,"categories":163,"keywords":164,"publishedAt":38},"01M6HBSY65SB29J9WE9KYD0K6T","api-security-review","Reviews Azure API Management configurations for security vulnerabilities, OWASP API Security Top 10 compliance, VNet Internal mode validation, Private Link verification, and Azure Security Benchmark alignment. Use when performing security audits, pre-deployment validation, or compliance reviews.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapi-security-review\u002FSKILL.md",[],[21,37,165,27,152,166,100,125,167,168,169,170,108,171,115,172,173,174,116,117],"security review","api security review","benchmark","verification","owasp","owasp-api","alignment","azure security","reviews","top",{"skillNo":176,"name":177,"nameZh":6,"description":178,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":179,"categories":180,"keywords":181,"publishedAt":38},"01M6HBSRW4PDFE6K4F8JYPZQ05","jira-cli","Interact with Jira from the command line to create, list, view, edit, and transition issues, manage sprints and epics, and perform common Jira workflows. Use when the user asks about Jira tasks, tickets, issues, sprints, or needs to manage project work items.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fjira-cli\u002FSKILL.md",[],[182,183,184,127,185,186,187,188,27,189,190,191,192,193,194,195,196,33,197,198],"cli","jira","jira cli","init","tasks","create","issues","common","work","command","edit","list","view","project","project work","line","sprints",{"skillNo":200,"name":201,"nameZh":6,"description":202,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":203,"categories":204,"keywords":205,"publishedAt":38},"01M6HBSNS3JHMW603G47TWE31H","calculator","Performs arbitrary-precision arithmetic calculations including addition, subtraction, multiplication, division, and exponents. Use when the user asks to calculate, compute, or evaluate math expressions, or when precise decimal arithmetic is needed to avoid floating-point errors.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fcalculator\u002FSKILL.md",[],[201,206,207,208,209,210,211,150,212,213],"npm","js","calculate","node","math","user","compute","errors"]