> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fraudeg.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Detect and Prevent Account Takeover Attacks in Real Time

> Integrate FraudEG to detect credential stuffing, session hijacking, and suspicious login behavior to protect your users from account takeover.

Account takeover (ATO) happens when an attacker gains unauthorized access to a legitimate user's account — typically by using stolen credentials, hijacked session tokens, or social engineering. Once inside, attackers change contact details, drain stored value, initiate fraudulent transfers, or use the account as a launchpad for downstream fraud. FraudEG detects ATO at every critical touchpoint in the user lifecycle: login, account settings changes, and high-value actions, giving you the signals you need to challenge suspicious actors before damage is done.

## Attack vectors FraudEG detects

FraudEG's ATO detection covers the most common attack patterns seen across financial, e-commerce, and SaaS platforms:

* **Credential stuffing** — automated login attempts using username/password pairs leaked from other breaches
* **Brute force** — high-volume attempts against a single account to guess a password
* **Session hijacking** — an attacker replays or steals a valid session token to impersonate a logged-in user
* **SIM swap** — a telecom social engineering attack that redirects a victim's phone number, bypassing SMS-based 2FA
* **Social engineering** — manipulation of support staff or the user themselves to gain account access

## Where to integrate

ATO protection is most effective when applied at three specific integration points:

1. **Login events** — score every login attempt, not just failed ones. Successful logins with anomalous signals are often the most dangerous.
2. **Account settings changes** — password resets, email address changes, phone number updates, and 2FA method changes are the first actions an attacker takes after gaining access.
3. **High-value actions** — withdrawal requests, payout address changes, and large transfers warrant independent risk scoring regardless of session age.

## Integration guide

<Steps>
  <Step title="Add the FraudEG SDK to your login and account pages">
    Include the FraudEG JavaScript SDK on every page where login or account management occurs. The SDK collects passive behavioral signals — typing cadence, mouse movement patterns, device fingerprint, and browser environment — that feed into the ATO risk model.

    ```html theme={null}
    <script>
      (function(f,r,a,u,d,e,g){
        f['FraudEGObject']=d;
        f[d]=f[d]||function(){ (f[d].q=f[d].q||[]).push(arguments) };
        e=r.createElement(a); e.async=1;
        e.src='https://cdn.fraudeg.com/v1/sdk.js';
        g=r.getElementsByTagName(a)[0];
        g.parentNode.insertBefore(e,g);
      })(window,document,'script','','fraudeg');

      fraudeg('init', 'YOUR_PUBLIC_KEY');
      fraudeg('session', function(sessionId) {
        document.getElementById('fraudeg_session').value = sessionId;
      });
    </script>
    ```

    Capture the `session_id` from the SDK callback and pass it to your backend with every login or account action request.
  </Step>

  <Step title="Score the login event">
    When a login attempt occurs, call `POST /v1/transactions/score` with `event_type: "login"` before completing authentication. Include the user identifier, device, IP, and session data.

    <CodeGroup>
      ```javascript Node.js theme={null}
      async function scoreLoginEvent({ userId, email, ipAddress, sessionId }) {
        const response = await fetch('https://api.fraudeg.com/v1/transactions/score', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${process.env.FRAUDEG_API_KEY}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            event_type: 'login',
            user: {
              id: userId,
              email: email,
              ip_address: ipAddress
            },
            session_id: sessionId
          })
        });
        return response.json();
      }
      ```

      ```python Python theme={null}
      import os
      import httpx

      async def score_login_event(user_id: str, email: str, ip_address: str, session_id: str) -> dict:
          async with httpx.AsyncClient() as client:
              response = await client.post(
                  "https://api.fraudeg.com/v1/transactions/score",
                  headers={
                      "Authorization": f"Bearer {os.environ['FRAUDEG_API_KEY']}",
                      "Content-Type": "application/json",
                  },
                  json={
                      "event_type": "login",
                      "user": {
                          "id": user_id,
                          "email": email,
                          "ip_address": ip_address,
                      },
                      "session_id": session_id,
                  },
              )
              response.raise_for_status()
              return response.json()
      ```
    </CodeGroup>
  </Step>

  <Step title="Act on the decision">
    Branch on the `decision` field returned in the scoring response:

    * **`allow`** — the login matches expected patterns. Complete authentication normally.
    * **`challenge`** — the login shows suspicious signals. Require step-up authentication before granting access: an SMS OTP, authenticator app TOTP, or email verification code.
    * **`block`** — the login matches a known attack pattern. Deny access, lock the account to prevent further attempts, and send a security alert to the account owner.

    ```javascript Node.js theme={null}
    const result = await scoreLoginEvent(loginData);

    switch (result.decision) {
      case 'allow':
        return completeLogin(userId);
      case 'challenge':
        return requireMFA({ userId, transactionId: result.transaction_id });
      case 'block':
        await lockAccount(userId);
        await notifyAccountOwner(userId, 'suspicious_login_blocked');
        return { error: 'Login blocked due to suspicious activity' };
    }
    ```
  </Step>

  <Step title="Score high-risk account actions">
    Apply the same scoring pattern to sensitive account operations. When a user attempts to change their password, update their email address, modify their 2FA configuration, or change a payout destination, call `POST /v1/transactions/score` with the appropriate `event_type` before executing the change.

    ```javascript Node.js theme={null}
    // Score before applying a password change
    const result = await fetch('https://api.fraudeg.com/v1/transactions/score', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.FRAUDEG_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        event_type: 'account_settings_change',
        change_type: 'password_reset',
        user: { id: userId, email: userEmail, ip_address: ipAddress },
        session_id: sessionId
      })
    }).then(r => r.json());
    ```
  </Step>

  <Step title="Subscribe to the account.risk_detected webhook">
    FraudEG also emits asynchronous risk signals when it detects ATO-indicative patterns across sessions — such as an account being accessed from multiple geographies simultaneously. Subscribe to the `account.risk_detected` event to react to these signals in your backend without polling.

    ```bash cURL theme={null}
    curl -X POST https://api.fraudeg.com/v1/webhooks \
      -H "Authorization: Bearer $FRAUDEG_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "url": "https://yourapp.com/webhooks/fraudeg",
        "events": ["account.risk_detected"],
        "description": "ATO risk signal handler"
      }'
    ```

    When you receive an `account.risk_detected` event, trigger your account protection workflow: force re-authentication, notify the user, and optionally suspend the session until the user confirms their identity.
  </Step>
</Steps>

## Key ATO signals

The `signals` array in the scoring response tells you exactly which risk factors influenced the decision. The following signals are most relevant to account takeover:

| Signal                        | Meaning                                                                                          |
| ----------------------------- | ------------------------------------------------------------------------------------------------ |
| `behavioral_anomaly`          | Typing, mouse, or interaction patterns differ significantly from the user's baseline             |
| `new_device`                  | The login originates from a device not previously associated with this account                   |
| `credential_stuffing_pattern` | Login attempt matches automated credential stuffing tooling characteristics                      |
| `impossible_travel`           | The user appears in two geographically distant locations within an implausibly short time window |
| `ip_reputation_high_risk`     | The request IP is associated with proxies, VPNs, Tor exit nodes, or known fraud infrastructure   |

<Note>
  Impossible travel detection compares the current login's IP geolocation against the user's most recent successful login. If the physical distance between the two locations cannot be covered in the elapsed time, FraudEG surfaces the `impossible_travel` signal. This catches session-sharing and credential handoff between attackers in different regions. You can tune the sensitivity of this check per user segment in your FraudEG dashboard settings.
</Note>

<Warning>
  Do not limit ATO scoring to login events alone. The most destructive phase of an account takeover — draining funds, locking out the legitimate user, redirecting payouts — happens **after** a successful login. Score every sensitive account action as its own event, and treat any `challenge` or `block` decision on a post-login action as a strong indicator that the session may already be compromised.
</Warning>

## Related resources

<CardGroup cols={3}>
  <Card title="Behavioral Analysis" icon="brain" href="/concepts/behavioral-analysis">
    Learn how FraudEG builds user behavior baselines and detects anomalies at login and beyond.
  </Card>

  <Card title="Device Intelligence" icon="laptop" href="/concepts/device-intelligence">
    Understand device fingerprinting, emulator detection, and how device signals factor into ATO scoring.
  </Card>

  <Card title="Webhooks" icon="webhook" href="/guides/webhooks">
    Set up real-time event delivery for asynchronous ATO signals and account risk alerts.
  </Card>
</CardGroup>
