Using Webhooks to Detect and Respond to Suspicious Login Events on Mail Providers
how-toapisecurity

Using Webhooks to Detect and Respond to Suspicious Login Events on Mail Providers

UUnknown
2026-02-24
9 min read
Advertisement

Detect suspicious Gmail logins and trigger automated security responses using Google Workspace alerts, Pub/Sub/webhooks, OAuth controls and SIEM integration.

Stop chasing alerts: automatically detect suspicious Gmail logins and neutralize threats

Security teams and platform engineers in 2026 face the same core problem: there are more ways for accounts to be compromised and fewer minutes to respond. You need to detect suspicious login events as close to real time as possible and trigger deterministic, auditable responses: revoke tokens, suspend accounts, rotate keys, update DNS and feed your SIEM — without manual toil. This guide gives a practical, production-ready pattern using Google Workspace (Gmail) signals, Pub/Sub/webhook delivery, OAuth domain delegation, and concrete automation recipes you can reuse for other providers.

Why this matters now (2026 context)

By late 2025 major providers accelerated webhook and push integrations for security telemetry. Google Workspace's Alert Center and Admin/Reports signals are routinely forwarded to Pub/Sub or webhook endpoints, and Microsoft extended Graph change notifications and signIn export pipelines — meaning you can build event-driven security responses rather than slow, error-prone manual playbooks.

Fast detection + automatic, scoped mitigation reduces dwell time and blast radius — the two metrics security teams care about most in 2026.

High-level architecture

Implement the following event-driven pipeline:

  • Event sources: Google Workspace Alert Center (suspicious login alerts), Admin SDK Reports API (login events), Cloud Audit Logs
  • Delivery: Alert Center & Audit Logs -> Pub/Sub (or webhook)
  • Webhook receiver: Cloud Function / server endpoint validates message, enriches it (user, device, IP), writes to SIEM, and triggers response playbook
  • Response actions: revoke OAuth tokens, suspend user, rotate DKIM, update DNS blocklists, create incident in ticketing system

Prerequisites & permissions

  1. A Google Workspace organization admin account.
  2. A GCP project with Pub/Sub and Cloud Functions (or your webhook stack).
  3. A service account configured for domain-wide delegation with these common scopes:
    • https://www.googleapis.com/auth/admin.reports.audit.readonly (Reports API)
    • https://www.googleapis.com/auth/admin.directory.user (user suspend/patch)
    • https://www.googleapis.com/auth/admin.directory.user.security (token management)
    • https://www.googleapis.com/auth/apps.alerts (Alert Center)
  4. Access to DNS provider API (Cloud DNS, Cloudflare, AWS Route 53, etc.) if you automate domain-level DNS changes.

Step 1 — Subscribe Alert Center to Pub/Sub (delivery)

Alert Center can forward specific security alerts (including suspicious login, suspicious device, suspicious OAuth grant) to a Pub/Sub topic. Configure a topic per environment and use fine-grained IAM so only Alert Center can publish.

  1. Create a Pub/Sub topic: gcloud pubsub topics create workspace-alerts
  2. Grant the Alert Center producer role to the Workspace service identity for that topic.
  3. In Admin console > Security > Alert Center, configure forwarding to the Pub/Sub topic for the alert types you want.

Why Pub/Sub?

Pub/Sub decouples the producer from your processing logic, offers retry/backoff, and integrates with Cloud Functions or your webhook stack. If you prefer direct webhooks, ensure the sender signs messages (OIDC tokens) and validate them.

Step 2 — Build the webhook/processor (Node.js example)

The receiver must:

  • Authenticate/validate the push (verify OIDC token or use Pub/Sub subscription pull)
  • Enrich event with Directory API lookup (user details, 2FA state)
  • Map event to response playbook
  • Forward structured alert to SIEM
  • Execute atomic mitigation actions via Google Admin SDK / DNS APIs
// Minimal Cloud Function (Node.js) to receive Pub/Sub push
const {google} = require('googleapis');
const axios = require('axios');

exports.workspaceAlertHandler = async (req, res) => {
  try {
    const message = req.body.message ? Buffer.from(req.body.message.data, 'base64').toString() : null;
    if (!message) return res.status(400).send('no message');

    const alert = JSON.parse(message);
    // basic validation — improve with OIDC token verification in production

    // Enrich: lookup user
    const userEmail = alert.alert_metadata ? alert.alert_metadata['primaryEmail'] : alert.userEmail;
    const authClient = await getAuthorizedClient(); // service account domain-delegated
    const directory = google.admin({version: 'directory_v1', auth: authClient});
    const user = await directory.users.get({userKey: userEmail});

    // Map to playbook
    const action = decideAction(alert, user.data);

    // Send to SIEM
    await axios.post(process.env.SIEM_HEC_URL, {alert, user: user.data});

    // Execute mitigation
    if (action === 'suspend') {
      await directory.users.patch({userKey: userEmail, requestBody: {suspended: true}});
      await revokeUserTokens(directory, userEmail);
    }

    res.status(200).send('ok');
  } catch (err) {
    console.error(err);
    res.status(500).send('error');
  }
};

async function getAuthorizedClient() {
  // Create JWT auth with domain-wide delegation (omitted for brevity)
}

async function revokeUserTokens(directory, userEmail) {
  // Use tokens API to delete OAuth tokens for user
  // directory.tokens.delete({userKey: userEmail, clientId: 'CLIENT_ID'});
}

Replace environment-specific details with your signing and SIEM configuration. The function demonstrates the key flow: validate → enrich → alarm → mitigate.

Step 3 — Common automated mitigation actions

Below are actions you can trigger programmatically. Every action should be scoped (least privilege) and reversible. Log everything to your SIEM and ticketing system.

  • Revoke OAuth tokens: call the Admin Directory tokens.delete for the OAuth client or use the token revocation endpoint. This stops token-based mailbox access immediately.
  • Suspend user: Directory API users.patch set suspended=true. This prevents logins but preserves account data for further investigation.
  • Force password reset: set a random password and mark the account to require a reset, or use your identity provider's forced-change flag.
  • Block sign-in from IP / country: update your organization’s login whitelist or use Context-Aware Access policies.
  • Rotate DKIM keys / quarantine mail: alter DNS TXT records and DMARC policy to reduce outbound delivery while investigating (e.g., p=quarantine).
  • Update SPF/Blocklists: add temporary TXT records to block suspicious outbound delivery paths.
  • Notify affected services: revoke app-specific API keys, shutdown CI runners tied to the account, and rotate secrets stored in the breached mailbox.

Example: revoke tokens and suspend user (Python snippet)

from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = [
    'https://www.googleapis.com/auth/admin.directory.user',
    'https://www.googleapis.com/auth/admin.directory.user.security',
]

SERVICE_ACCOUNT_FILE = '/secrets/service-account.json'
DELEGATED_ADMIN = 'admin@example.com'

credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
credentials = credentials.with_subject(DELEGATED_ADMIN)

directory = build('admin', 'directory_v1', credentials=credentials)

# suspend user
directory.users().patch(userKey='alice@example.com', body={'suspended': True}).execute()

# revoke tokens for a specific OAuth client id
directory.tokens().delete(userKey='alice@example.com', clientId='1234567890.apps.googleusercontent.com').execute()

Step 4 — SIEM and incident enrichment

Always forward enriched events to your SIEM. Include these fields at minimum:

  • timestamp
  • user.email
  • event.type (suspicious_login, oauth_grant, login_failure)
  • ip.address / geolocation
  • device.platform / os
  • action_taken (revoke, suspend, dmarc_change)
  • correlation_id

Example: Splunk HEC ingest (curl):

curl -k https://splunk.example.com:8088/services/collector -H 'Authorization: Splunk $HEC_TOKEN' \
  -d '{"event": {"type":"suspicious_login","user":"alice@example.com","ip":"1.2.3.4"}}'

Playbook: map signal to response

Keep it simple and deterministic. Example mapping:

  • High confidence suspicious login (new country + new device + multiple failed attempts): suspend user + revoke tokens + create incident ticket
  • Medium confidence (one indicator, unknown device): revoke tokens + force password reset + alert SOC analyst
  • Low confidence (failed login from known VPN IP): increase monitoring, notify user)

Testing, observability and safety

  • Canary mode: deploy actions as "dry run" to log intended actions without executing. Promote to active after verification.
  • Idempotency: ensure your webhook handler is idempotent. Use correlation IDs to avoid doubling actions on retry.
  • Audit trail: write all decisions and API responses to an append-only incident log stored in your SIEM and GCS with retention policy aligned to compliance needs.
  • Rate limits & backoff: calls to Admin SDK / DNS APIs should implement exponential backoff and circuit breakers to avoid causing outages.

OAuth, tokens and best practices (strong recommendations)

  • Enforce least privilege for service accounts and refresh tokens.
  • Use domain-wide delegation only for specific scopes and restrict the service account’s access to only the admin subject required.
  • Monitor OAuth client usage and auto-revoke apps that request risky scopes or unusual behavior.
  • Log OAuth token issuance and refresh rates to detect automated credential stuffing or token replay.

Extending to other mail providers

Most enterprise email providers now offer a combination of sign-in logs, alerts, and push/export mechanisms:

  • Microsoft 365 / Azure AD — signIn logs in Azure AD can be exported to Event Hubs / Log Analytics or consumed via Microsoft Graph change notifications. Use the Graph Security API for alerts and automate responses using MS Graph to disable accounts, revoke refresh tokens, and quarantine mailboxes.
  • Third-party providers — many lack rich webhooks. Use IMAP/POP login monitoring, SMTP logs, or supplier-specific APIs. If no push exists, poll the audit logs at a short cadence with careful rate-limiting.

Advanced strategies (2026 and beyond)

  • Combine signals: correlate Gmail/Workspace signals with endpoint telemetry, SSO logs, and network logs. A probabilistic scoring model reduces false positives and informs response severity.
  • Automated DKIM rotation: integrate your DNS provider API to rotate DKIM keys programmatically and add a phased rollout to avoid mail loss.
  • Policy-as-code: keep playbooks in Git, review and deploy via CI/CD pipelines, and run automated policy tests against staging directories.
  • Machine learning: use anomaly detection in your SIEM to create alerts that your webhook handler consumes; keep human-in-the-loop for high-impact actions.

Privacy, compliance and governance

Automated responses manipulate user accounts and potentially DNS and mail flow. Limit access, maintain approvals for destructive actions, and keep a retention policy for logs. Ensure you’re auditing who triggered what and when, and expose a manual override for false positives.

Checklist: deploy in 4 sprints

  1. Week 1: Configure Alert Center & Pub/Sub, create service account with domain delegation, and build a read-only webhook to log incoming alerts to SIEM.
  2. Week 2: Implement enrichment calls (Directory API) and a dry-run playbook that logs intended mitigations.
  3. Week 3: Add safe mitigation actions (revoke tokens, suspend user) behind feature flags and escalation to SOC.
  4. Week 4: Harden: add idempotency, backoff, audit trail, and integrate DNS rotation and ticketing automation.

In 2026 the best security teams are event-driven: they detect signals at the source (Gmail/Workspace, Azure AD), push them into resilient messaging (Pub/Sub/Event Hubs), and respond with precise, reversible automations. Start small (dry runs), measure false-positive rates, and iterate your playbook into production. Prioritize actions that reduce blast radius quickly: revoke tokens and suspend accounts before changing global DNS or DKIM unless you’re sure mail quarantine is required.

Actionable takeaways:

  • Subscribe Alert Center to Pub/Sub for robust delivery.
  • Use a service account with domain-wide delegation to enrich and act on alerts.
  • Map signals to deterministic playbooks (revoke, suspend, notify) and log everything to your SIEM.
  • Test in canary mode and add human gates for high-impact actions.

Call to action

Ready to deploy this pattern in your environment? Download our starter repo with Cloud Function templates, SIEM connectors, and playbook examples — or contact our automation engineers at registrer.cloud for a 2‑week workshop to integrate Gmail/Workspace alerts into your incident response pipeline.

Advertisement

Related Topics

#how-to#api#security
U

Unknown

Contributor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.

Advertisement
2026-02-24T02:40:07.492Z