Per-user two-factor auth in CakePHP with CakeDC/Users (opt-in, one method)
CakeDC/Users gives you TOTP two-factor authentication almost for free: flip one config key and every login grows a "enter your 6-digit code" step. The catch is that word every . The built-in flow is all-or-nothing — turn it on and all your users are forced through the OTP challenge on their next login, whether they ever set up an authenticator app or not. Lock yourself out on a fresh install and…
Two-factor authentication (2FA) in the CakePHP framework can be implemented using the CakeDC/Users package with a per-user approach that allows users to opt-in individually. Instead of forcing all users to enable 2FA, this method lets each user decide whether to use it or not. The default rules are kept intact, and only a single method is overridden to add the per-user flag.
A new boolean column called "two_steps" is added to the users table, which indicates whether a user has opted-in for 2FA. Existing users remain unaffected, while new users start with 2FA disabled. The OneTimePasswordAuthenticationChecker interface is swapped to include the new per-user flag check. This allows the 2FA challenge to be displayed only for users who have opted-in.
The QR code generation for enrollment uses the BaconQrCodeProvider instead of the default EndroidQrCodeProvider to avoid compatibility issues with modern dependencies. This provider generates the QR code as an SVG image, which can be embedded directly into the template without any file writes. The two-factor authentication flow then allows a signed-in user to generate a secret, display the QR code, and type a 6-digit code to enable 2FA without needing a logout round-trip.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.