How to Implement TOTP 2FA in Rails using ROTP
2 days ago
- - The post explains how to implement TOTP (Time-based One-Time Password) two-factor authentication (2FA) in a Rails app using the ROTP gem.
- - It starts by reviewing the existing API key authentication flow and then creates a new `second_factors` table and model with an encrypted OTP secret.
- - The implementation includes CRUD operations for managing second factors, with verification requiring a password or OTP depending on whether 2FA is already enabled.
- - The authentication flow is adjusted to require an OTP when a user has a second factor enabled, returning specific error codes like `OTP_REQUIRED` and `OTP_INVALID`.
- - A provisioning URI is generated for QR code scanning to set up TOTP in authenticator apps, and the second factor must be verified with a valid OTP before enabling.
- - The post addresses a vulnerability by adding an `otp_verified_at` column to prevent OTP reuse, ensuring tokens are one-time use only.