MFA & Passwordless
๐ฅ Vibe Prompt
"Implement TOTP MFA, WebAuthn passkeys, and risk-based authentication."
TOTP (Time-based One-Time Password)
import pyotp
import qrcode
# Generate secret
secret = pyotp.random_base32()
print(f"Secret: {secret}")
# Create provisioning URI (for QR code)
totp = pyotp.TOTP(secret)
uri = totp.provisioning_uri(name="alice@example.com", issuer_name="MyApp")
print(f"QR URI: {uri}")
# Generate QR code
qr = qrcode.make(uri)
qr.save("totp_qr.png")
# Verify
code = input("Enter TOTP code: ")
if totp.verify(code):
print("โ
TOTP valid!")
else:
print("โ Invalid code")
# Verify with drift tolerance (30s window)
if totp.verify(code, valid_window=1):
print("โ
Valid within 30s window")
WebAuthn / Passkeys
// Registration (browser)
const credential = await navigator.credentials.create({
publicKey: {
challenge: new Uint8Array([...]), // From server
rp: { name: "MyApp", id: "example.com" },
user: {
id: new Uint8Array([1,2,3]),
name: "alice@example.com",
displayName: "Alice"
},
pubKeyCredParams: [{ type: "public-key", alg: -7 }], // ES256
authenticatorSelection: {
authenticatorAttachment: "platform", // Built-in (Touch ID, Face ID)
residentKey: "required", // Discoverable credential
userVerification: "required"
}
}
});
// Authentication
const assertion = await navigator.credentials.get({
publicKey: {
challenge: new Uint8Array([...]), // From server
rpId: "example.com",
allowCredentials: [{type: "public-key", id: credentialId}],
userVerification: "required"
}
});
Risk-Based Authentication (RBA)
def calculate_risk(user, request):
score = 0
# Location
if request.geo.country != user.known_countries:
score += 30
# Device
if request.user_agent not in user.known_devices:
score += 20
# Time
if 2 <= datetime.now().hour <= 5: # 2-5 AM
score += 15
# IP reputation
if is_vpn_or_tor(request.ip):
score += 25
# Failed attempts
if user.failed_logins_last_hour > 3:
score += 10
# Decision
if score > 70:
return "BLOCK"
elif score > 40:
return "CHALLENGE_MFA" # Require MFA
else:
return "ALLOW"
MFA Methods Comparison
| Method | UX | Security | Phishing Resistant | |--------|-----|----------|--------------------| | TOTP (Google Auth) | Medium | High | No | | SMS (SMS OTP) | Good | Low | No | | Push (Duo) | Good | High | No | | WebAuthn/Passkeys | Best | Highest | Yes | | Security Key (FIDO2) | Medium | Highest | Yes |
Best Practices
- Offer WebAuthn as primary (best UX + security)
- TOTP as fallback
- Avoid SMS MFA (SS7 attacks, SIM swap)
- Require MFA for all admin/privileged actions
- Step-up auth for sensitive operations (payments)
- Remember trusted devices (cookie + device fingerprint)