Security

Configure password policies, brute force protection, and audit logging.

Overview

Transactional Auth provides comprehensive security features to protect user accounts and detect threats. Configure policies, monitor activity, and respond to security events.

Password Policies

Configure Password Requirements

TypeScript:

await client.auth.security.updatePasswordPolicy({
  minLength: 12,
  requireUppercase: true,
  requireLowercase: true,
  requireNumbers: true,
  requireSymbols: true,
  checkBreached: true, // Check against known breach databases
  preventReuse: 5, // Prevent last 5 passwords
});

Python:

client.auth.security.update_password_policy(
    min_length=12,
    require_uppercase=True,
    require_lowercase=True,
    require_numbers=True,
    require_symbols=True,
    check_breached=True,
)

Password Options

OptionDescriptionDefault
minLengthMinimum password length8
maxLengthMaximum password length128
requireUppercaseRequire uppercase letterfalse
requireLowercaseRequire lowercase letterfalse
requireNumbersRequire numberfalse
requireSymbolsRequire special characterfalse
checkBreachedCheck against breach databasesfalse
preventReuseNumber of previous passwords to block0

Breached Password Detection

When enabled, passwords are checked against known breach databases:

// During password change
try {
  await client.auth.users.changePassword(userId, {
    newPassword: 'password123', // Common breached password
  });
} catch (error) {
  // Error: Password found in breach database
  console.log(error.code); // 'PASSWORD_BREACHED'
}

Brute Force Protection

Protect against automated attacks.

Configure Protection

await client.auth.security.updateBruteForcePolicy({
  maxAttempts: 5,
  lockoutDuration: 15, // minutes
  trackingWindow: 10, // minutes
  enabled: true,
});

Protection Options

OptionDescriptionDefault
maxAttemptsFailed attempts before lockout5
lockoutDurationLockout time in minutes15
trackingWindowTime window for counting attempts10
ipBasedTrackingTrack attempts by IPtrue
userBasedTrackingTrack attempts by usertrue

Lockout Behavior

When locked out:

  1. User cannot log in
  2. API returns specific error code
  3. User receives email notification (if configured)
  4. Admin can manually unlock

Unlock User

// Check lockout status
const status = await client.auth.security.getLockoutStatus('user_xxx');
console.log('Locked:', status.isLocked);
console.log('Attempts:', status.failedAttempts);
console.log('Unlocks at:', status.unlocksAt);
 
// Manual unlock
await client.auth.security.unlockUser('user_xxx');

Session Security

Configure Session Policies

await client.auth.security.updateSessionPolicy({
  maxConcurrent: 3, // Max active sessions per user
  idleTimeout: 60, // Inactivity timeout (minutes)
  absoluteTimeout: 480, // Max session duration (minutes)
  requireReauth: ['password_change', 'delete_account'], // Actions requiring re-auth
});

Session Options

OptionDescriptionDefault
maxConcurrentMax simultaneous sessions (0 = unlimited)0
idleTimeoutInactivity timeout in minutes60
absoluteTimeoutMax session duration (0 = unlimited)0
invalidateOnPasswordChangeRevoke sessions on password changetrue

IP Restrictions

Allowlist IPs

Only allow access from specific IPs:

await client.auth.security.updateIpPolicy({
  mode: 'ALLOWLIST',
  addresses: [
    '203.0.113.0/24', // CIDR notation
    '198.51.100.1',   // Single IP
  ],
});

Blocklist IPs

Block specific IPs:

await client.auth.security.updateIpPolicy({
  mode: 'BLOCKLIST',
  addresses: [
    '192.0.2.0/24',
  ],
});

Anomaly Detection

Detect suspicious login activity.

Configure Detection

await client.auth.security.updateAnomalyPolicy({
  newDeviceAlert: true,
  newLocationAlert: true,
  suspiciousIpBlocking: true,
  impossibleTravel: true, // Login from impossible distance
});

Anomaly Actions

TriggerDefault Action
New deviceEmail notification
New locationEmail notification
Suspicious IPBlock + notification
Impossible travelMFA challenge

Handle Anomaly Events

// Webhook handler
app.post('/webhooks/auth', async (req, res) => {
  const event = req.body;
 
  if (event.type === 'login.anomaly_detected') {
    const { user, anomalyType, risk } = event.data;
 
    if (risk === 'HIGH') {
      // Force re-authentication
      await client.auth.sessions.revokeAll(user.id);
      await notifySecurityTeam(event);
    }
  }
});

Bot Protection

Prevent automated attacks on login forms.

CAPTCHA Integration

await client.auth.security.updateBotPolicy({
  captchaProvider: 'RECAPTCHA_V3',
  captchaSiteKey: 'your-site-key',
  captchaSecretKey: 'your-secret-key',
  threshold: 0.5, // Score threshold
  showOn: ['login', 'signup', 'password_reset'],
});

Supported Providers

  • reCAPTCHA v2
  • reCAPTCHA v3
  • hCaptcha
  • Cloudflare Turnstile

Audit Logging

Track all security-related events.

Query Audit Logs

const logs = await client.auth.logs.query({
  startDate: '2024-01-01',
  endDate: '2024-01-31',
  eventTypes: ['login.success', 'login.failed', 'password.reset'],
  userId: 'user_xxx',
  count: 100,
});
 
for (const log of logs) {
  console.log(`${log.timestamp}: ${log.eventType}`);
  console.log(`  User: ${log.userId}`);
  console.log(`  IP: ${log.ipAddress}`);
  console.log(`  Details:`, log.details);
}

Log Retention

await client.auth.security.updateLogPolicy({
  retentionDays: 90, // Keep logs for 90 days
  exportEnabled: true, // Allow log export
});

Export Logs

const export = await client.auth.logs.export({
  format: 'json', // or 'csv'
  startDate: '2024-01-01',
  endDate: '2024-01-31',
});
 
console.log('Download URL:', export.url);

Security Notifications

Configure security-related notifications.

User Notifications

await client.auth.security.updateNotifications({
  newLogin: true, // Notify on new device login
  passwordChanged: true,
  mfaEnabled: true,
  mfaDisabled: true,
  accountLocked: true,
});

Admin Alerts

await client.auth.security.updateAdminAlerts({
  enabled: true,
  email: 'security@yourcompany.com',
  alertOn: [
    'BRUTE_FORCE_DETECTED',
    'SUSPICIOUS_ACTIVITY',
    'MULTIPLE_FAILED_MFA',
  ],
});

Security Dashboard

Get Security Overview

const overview = await client.auth.security.getOverview({
  period: '30d',
});
 
console.log('Total logins:', overview.totalLogins);
console.log('Failed logins:', overview.failedLogins);
console.log('Blocked attempts:', overview.blockedAttempts);
console.log('MFA adoption:', overview.mfaAdoptionRate);
console.log('Password reset:', overview.passwordResets);

Get Threat Summary

const threats = await client.auth.security.getThreatSummary();
 
for (const threat of threats) {
  console.log(`${threat.type}: ${threat.count} incidents`);
  console.log(`  Risk level: ${threat.riskLevel}`);
  console.log(`  Top IPs:`, threat.topIpAddresses);
}

Security Recommendations

1. Enforce Strong Passwords

// Recommended password policy
await client.auth.security.updatePasswordPolicy({
  minLength: 12,
  requireUppercase: true,
  requireLowercase: true,
  requireNumbers: true,
  checkBreached: true,
  preventReuse: 5,
});

2. Enable MFA

// Require MFA for all users
await client.auth.mfa.updatePolicy({
  requirement: 'REQUIRED',
  allowedFactors: ['TOTP', 'WEBAUTHN'],
  gracePeriod: { value: 7, unit: 'DAYS' },
});

3. Monitor Activity

  • Enable audit logging
  • Set up admin alerts
  • Review logs regularly
  • Export for compliance

4. Limit Sessions

await client.auth.security.updateSessionPolicy({
  maxConcurrent: 5,
  idleTimeout: 30,
  absoluteTimeout: 240,
});

Next Steps