Multi-Factor Authentication
Passwords alone aren't enough. They get phished, reused across sites, and leaked in breaches. Multi-factor authentication (MFA) adds additional verification — something you have or something you are — making account compromise significantly harder.
MFA Methods Compared
TOTP (Time-based One-Time Password) generates codes that change every 30 seconds. Apps like Google Authenticator or Authy store the secret and generate codes offline. It's widely supported and reasonably secure.
SMS codes are convenient but vulnerable. Attackers can intercept messages through SIM swapping or SS7 network exploits. Use SMS only when better options aren't available.
Email codes share similar convenience and vulnerability trade-offs. They're better than nothing but shouldn't be your primary MFA method.
Hardware keys using WebAuthn/FIDO2 (like YubiKeys) provide the strongest protection. They're phishing-resistant because they verify the website's domain. The downside is cost and the need to carry a physical device.
Push notifications send approval requests to a trusted device. They're user-friendly but require network connectivity and can be vulnerable to "MFA fatigue" attacks where users approve prompts just to stop the notifications.
Implementing TOTP
TOTP is the most common MFA method to implement yourself:
import pyotp
# Generate secret for user (store securely in database)
secret = pyotp.random_base32()
# Generate QR code URL for authenticator apps
totp = pyotp.TOTP(secret)
uri = totp.provisioning_uri(
email,
issuer_name="MyApp"
)
# Display QR code of this URI to user
# Later, verify the code they enter
is_valid = totp.verify(user_input_code)
The secret must be stored securely — if attackers get it, they can generate valid codes.
User Experience Considerations
MFA adds friction, so design thoughtfully. Offer backup codes — pre-generated one-time codes users can store safely for when they lose their device. Remember trusted devices — don't require MFA on every login from known devices. Provide clear recovery — users will lose access to their second factor; have a secure recovery process ready.
Consider making MFA optional initially but strongly encouraged. Forcing it on all users can drive them away, while making it easy to enable increases adoption.