Skip to main content
ALTCHA®

Protecting login & authentication

Login forms are attacked with lists of leaked credentials, and a successful guess pays off directly, so they deserve stricter protection than a contact form. This page combines a strict widget policy with three backend checks: a signed widget verification, a per-account attempt limit, and a distance check against the account's last login location.

Prerequisites: a running Sentinel with an active license, widget 3.6.0 or later on the login page, and an admin user who can edit security groups and API keys. The location check also needs an IP resolver that returns coordinates.

What you're defending against

ThreatWhat stops it
Credential stuffing from scripts and headless browsersProof-of-work on every attempt, rate limits per device and IP, and Human Interaction Signature (HIS).
Attempts from data centers, proxies and TorA code challenge and a harder proof-of-work from the first request (network = hosting, risk, signals).
One client failing again and againEach failed verification raises the client's penalty; from 8, the Strict preset denies it. Your backend's reports of failed passwords add automatic threat entries.
Password spraying against one account from many IPsA per-account attempt limit, which you check from your backend with the classifier's rateLimit.
A stolen password used from another regionLOCATION_DISTANCE: the distance from the account's last login location, so your backend can ask for a second factor.

Security group for the login form

Create a public security group for login forms and apply the Strict base preset from Templates. Leave out the Form fields add-on: the widget would only send the username, which tells the text rules nothing.

Strict writes these rules:

RuleEffect
preset:strict:gateDenies clients with a penalty of 8 or more.
preset:strict:threatsDenies IPs with the threat verdict block, except on /v2/verify.
preset:strict:base30/10m per device and 300/1h per IP, HIS relaxed, challenges expire after 5m.
preset:strict:elevatedA code challenge and a harder proof-of-work for risk ≥ 3, a penalty of 2 or more, hosting networks, or the BOT, CLI, LIBRARY, MALICIOUS, PROXY and TOR signals.
preset:strict:highHIS strict, a longer code and the hardest proof-of-work for risk ≥ 6 or a penalty of 5 or more.

Add Trusted networks in front if your support staff log in from a known office network and shouldn't be escalated. See Presets: Strict for the exact rules.

Backend group

Your backend calls POST /v2/verify/signature, POST /v2/classifier and POST /v2/threat/_report with a restricted key. Put that key in a group with the Backend API (allowed IPs) preset. Each login then makes two or three calls from your backend's IP, so raise the global per-IP limit above your peak login rate:

[rate_limit]
global = "3000/1m"   # per client IP; your backend's IP counts every login attempt 2–3 times

See Backend & API protection and [rate_limit].

Integration steps

Step 1 — Add the widget to the login form

Install the widget in your page as described in Widget integration, and point it at Sentinel with the login group's public key:

<form action="/login" method="post">
  <input type="text" name="username" autocomplete="username" required />
  <input type="password" name="password" autocomplete="current-password" required />
  <altcha-widget
    challenge="https://sentinel.example.com/v2/challenge?apiKey=key_…&params.formId=login"
  ></altcha-widget>
  <button type="submit">Sign in</button>
</form>

Step 2 — Check the attempt before the password

Run Sentinel's checks before you hash the password, so a refused attempt costs you nothing:

  1. Verify the widget payload with POST /v2/verify/signature.
  2. Call POST /v2/classifier with the visitor's IP and headers, a rateLimit keyed by the account, and the account's lastKnownLocation. One hit counts against the limit per call. Sentinel keeps the counter per API key, or per account with rateLimit.scope account (as in the Backend API preset), so every replica of your app shares it.
import { createHash } from 'node:crypto';
import { verifyServer } from 'altcha-lib';
import express from 'express';

const SENTINEL = 'https://sentinel.example.com';
const KEY_ID = 'key_…'; // restricted key
const KEY_SECRET = process.env.SENTINEL_API_KEY_SECRET!;
const BASIC = 'Basic ' + Buffer.from(`${KEY_ID}:${KEY_SECRET}`).toString('base64');

async function sentinel(path: string, body: unknown) {
  const res = await fetch(SENTINEL + path, {
    method: 'POST',
    headers: { Authorization: BASIC, 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`Sentinel ${path}: ${res.status}`);
  return (await res.json()).data;
}

const app = express();
app.set('trust proxy', 1); // req.ip is the visitor's IP behind your load balancer
app.use(express.urlencoded({ extended: false }));

app.post('/login', async (req, res) => {
  const verification = await verifyServer({
    payload: req.body.altcha,
    url: `${SENTINEL}/v2/verify/signature`,
    apiKey: { id: KEY_ID, secret: KEY_SECRET },
  });
  const v = verification.verified ? verification.verificationData : null;
  if (!v || v['params.formId'] !== 'login' || v.classification === 'BAD') {
    res.status(400).send('Verification failed. Please try again.');
    return;
  }

  const username = String(req.body.username).trim().toLowerCase();
  const user = await findUser(username); // your code; may be null
  const check = await sentinel('/v2/classifier', {
    ip: req.ip,
    headers: {
      'user-agent': req.get('user-agent') ?? '',
      accept: req.get('accept') ?? '',
      'accept-language': req.get('accept-language') ?? '',
    },
    rateLimit: {
      limit: '5/15m,20/1d',
      // A hash keeps usernames out of Sentinel's KV store.
      customKey: 'login:' + createHash('sha256').update(username).digest('hex'),
    },
    lastKnownLocation: user?.lastLoginLocation ?? undefined, // { lat, lon }
  });
  if (check.rateLimit?.triggeredRules.includes('RATE_LIMIT')) {
    res.status(429).send('Too many attempts for this account. Try again later.');
    return;
  }

  if (!user || !(await checkPassword(user, req.body.password))) { // your code
    await sentinel('/v2/threat/_report', {
      ip: req.ip,
      limit: '20/10m',
      kind: 'malicious',
      reason: 'Failed login',
    });
    res.status(401).send('Wrong username or password.');
    return;
  }

  const distanceKm = check.location?.rules.LOCATION_DISTANCE.distanceKm ?? 0;
  if (check.ip?.lat != null && check.ip?.lon != null) {
    await saveLastLoginLocation(user, { lat: check.ip.lat, lon: check.ip.lon }); // your code
  }
  if (distanceKm >= 1000) {
    await startSecondFactor(req, res, user); // your code: OTP, passkey or email link
    return;
  }
  await startSession(req, res, user); // your code
});

app.listen(8080);
  • Per-account limit. 5/15m,20/1d allows 5 attempts per account in 15 minutes and 20 a day, successful ones included. The first exceeded limit makes the RATE_LIMIT rule score 10, and check.rateLimit also returns remainingPoints and resetInSec. Limits use the points/duration syntax of Rate limiting.
  • Failed-password reports. The 20th report for an IP within 10 minutes gives it an automatic block entry for 48h. The Strict preset's threats rule then denies the IP on the login widget, and on every other widget group with that rule. See Report abuse.
  • Distance. LOCATION_DISTANCE.distanceKm is the distance between the IP's coordinates and lastKnownLocation, or null when either is missing. Its rule score grows with the logarithm of the distance; the threshold of 1000 km above is yours to pick. Travel and VPNs cause real distances, so ask for a second factor rather than refusing the login.
  • Fail closed or open. The sentinel() helper throws on an error response. Decide whether your login refuses attempts or skips these checks while Sentinel is unreachable, and catch accordingly.

See the POST /v2/classifier API reference for the full response.

Monitoring & tuning

  • Test Strict in monitor mode. Apply it with Apply in monitor mode checked, and watch the group's Activity tab for how many attempts its gate, elevated and high rules would have denied or escalated. See Monitor mode.
  • Watch verification errors. With request logging on the login key, the error breakdown of POST /v2/request-logs/_stats counts HIS_BLOCKED, INCORRECT_CODE, TOO_FAST and ACCESS_DENIED. A rise during normal traffic means real users are caught; during an attack, it means the policy works.
  • Watch the per-account limit. With request logging set to All on the backend key, each POST /v2/classifier call is logged with its triggeredRules. Filter on RATE_LIMIT to see which periods hit the limit.
  • Alert on attacks. The verification_failures alert fires when failed verifications rise well above the account's baseline. During a sustained attack, switch the base preset to Lockdown, and back when it ends. See Alerts.
  • Unblock a false positive. A root user can set an automatic entry's action to allow, or delete it, under Threat Intelligence → Entries. See Threat intelligence.

The brute_force and user_brute_force alerts watch sign-ins to Sentinel's own admin UI, not your application's logins.

Start typing to search...

↑ ↓ Navigate ↵ Select