Lab 13: Two-Factor Authentication (2FA)
Additional Resources
Section titled “Additional Resources”- Understanding Two-Factor Authentication (2FA)
- User Login
- TOTP: Time-Based One-Time Password Algorithm (RFC 6238) ↗
- robthree/twofactorauth Library Documentation ↗
- OWASP Multi-Factor Authentication Cheat Sheet ↗
Overview
Section titled “Overview”In this lab, you will add Two-Factor Authentication (2FA) to the login system from Lab 9, using TOTP (Time-based One-Time Password) codes from an authenticator app. Users enable 2FA by scanning a QR code. From then on, a correct password is no longer enough to log in: the user is only logged in after also entering the 6-digit code from their phone.
Two optional extensions at the end add a “Remember this device” feature and make 2FA mandatory for administrators.
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will:
- Generate a TOTP secret and a QR code with the
robthree/twofactorauthlibrary. - Let users enable and disable 2FA, confirming each change.
- Split the login into two stages, so a user is only logged in after both the password and the code are verified.
- Limit the number of code attempts during login.
- Explain why the session ID is regenerated after the second factor is verified.
Prerequisites
Section titled “Prerequisites”Before starting this lab, ensure you have:
- Completed Lab 9: Login & Authentication, including
SessionManager::regenerate(),AuthMiddleware, and the user dashboard. - Completed Lab 4: Session Middleware and Flash Messages.
- Read Understanding Two-Factor Authentication (2FA).
- PHP 8.2 or later (required by version 3 of the library).
- A smartphone with Google Authenticator, Microsoft Authenticator, or Authy installed.
How the Login Works After This Lab
Section titled “How the Login Works After This Lab”In Lab 9, a correct password logged the user in immediately. With 2FA, the login has two stages:
POST /login (password correct) │ ├── 2FA disabled → log in, redirect to the dashboard (as in Lab 9) │ └── 2FA enabled → save only "2fa_pending_user_id" in the session redirect to /2fa/verify │ POST /2fa/verify (code correct) │ └── log in, redirect to the dashboardWhile the code has not been entered, the user is not logged in: is_authenticated is not set, so AuthMiddleware still blocks every protected page. Only the two /2fa/verify routes accept a pending login.
| Stage | What the code does |
|---|---|
Start a pending login (in authenticate()) | Issue a new session ID, save the user’s ID in the session as 2fa_pending_user_id, and redirect to 2fa.verify |
Complete the login (in verify()) | Remove 2fa_pending_user_id and 2fa_attempts from the session, log the user in with AuthSession::login(), and set a welcome flash message |
Step 1: Install the Required Packages
Section titled “Step 1: Install the Required Packages”Objective: Add the TOTP and QR code libraries to your project.
Instructions:
- Open a terminal in your project root
- Run the following commands:
composer require robthree/twofactorauthcomposer require bacon/bacon-qr-codeStep 2: Create the two_factor_auth Table
Section titled “Step 2: Create the two_factor_auth Table”Objective: Store each user’s TOTP secret.
Instructions:
- Open phpMyAdmin, select your project database, and click on the “SQL” tab
- Execute the following statement:
CREATE TABLE IF NOT EXISTS two_factor_auth ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, secret VARCHAR(255) NOT NULL, enabled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, UNIQUE KEY unique_user (user_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;A user has a row in this table only while 2FA is enabled. Enabling 2FA inserts the row, and disabling it deletes the row. Because of the UNIQUE key, each user has at most one secret.
Step 3: Create the TwoFactorAuthModel
Section titled “Step 3: Create the TwoFactorAuthModel”Objective: Create a model that enables, disables, and reads a user’s 2FA secret.
Instructions:
- Navigate to your
app/Domain/Models/directory - Create a new file named
TwoFactorAuthModel.php - Start from the following class structure:
<?php
declare(strict_types=1);
namespace App\Domain\Models;
use App\Helpers\Core\PDOService;
class TwoFactorAuthModel extends BaseModel{ public function __construct(PDOService $pdoService) { parent::__construct($pdoService); }
/** * Enable 2FA for the user by saving their secret. */ public function enable(int $userId, string $secret): void { // TODO: Insert a row into the two_factor_auth table with the // user_id and secret columns. }
/** * Disable 2FA for the user. */ public function disable(int $userId): void { // TODO: Delete the user's row from the two_factor_auth table. }
/** * Return true if the user has 2FA enabled. */ public function isEnabled(int $userId): bool { // TODO: Check whether the two_factor_auth table has a row // for this user_id. }
/** * Return the user's TOTP secret, or null if 2FA is disabled. */ public function getSecret(int $userId): ?string { // TODO: Return the secret column of the user's row in the // two_factor_auth table, or null if there is no row. }}- Implement the TODOs
- Save the file
Step 4: Move the Login Code into a Helper
Section titled “Step 4: Move the Login Code into a Helper”Objective: Make the code that logs a user in reusable, because both AuthController and the new TwoFactorController need it.
Instructions:
- Open
app/Domain/Models/UserModel.phpand add a method that finds a user by ID:
/** * Return the user with the given ID, or null if there is none. */public function findById(int $id): ?array{ // TODO: Look up a single user in the users table by its id column, // as findByEmail() does by email.}- Navigate to your
app/Helpers/directory and create a file namedAuthSession.php:
<?php
declare(strict_types=1);
namespace App\Helpers;
class AuthSession{ /** * Log the user in: issue a new session ID and store the user's session keys. */ public static function login(array $user): void { // TODO: Move here the code from your Lab 9 authenticate() method that // regenerates the session ID and stores the session keys // (user_id, user_email, user_name, user_role, is_authenticated). }}- Implement both TODOs
- In
AuthController::authenticate(), replace the moved code with a call toAuthSession::login($user) - Save the files and check that logging in still works exactly as in Lab 9
Step 5: Create the TwoFactorController
Section titled “Step 5: Create the TwoFactorController”Objective: Handle enabling 2FA, verifying the code during login, and disabling 2FA.
The following TwoFactorAuth and BaconQrCodeProvider methods are the ones you will need:
$qrProvider = new BaconQrCodeProvider(int $borderWidth, string $backgroundColour, string $foregroundColour, string $format);$tfa = new TwoFactorAuth(QRCodeProviderInterface $qrcodeprovider, string $issuer);$tfa->createSecret(): string;$tfa->getQRCodeImageAsDataUri(string $label, string $secret, int $size = 200): string;$tfa->verifyCode(string $secret, string $code): bool;Instructions:
- Navigate to your
app/Controllers/directory - Create a new file named
TwoFactorController.php - Start from the following class structure:
<?php
declare(strict_types=1);
namespace App\Controllers;
use App\Domain\Models\TwoFactorAuthModel;use App\Domain\Models\UserModel;use App\Helpers\AuthSession;use App\Helpers\FlashMessage;use App\Helpers\SessionManager;use DI\Container;use Psr\Http\Message\ResponseInterface as Response;use Psr\Http\Message\ServerRequestInterface as Request;use RobThree\Auth\Providers\Qr\BaconQrCodeProvider;use RobThree\Auth\TwoFactorAuth;
class TwoFactorController extends BaseController{ private const MAX_ATTEMPTS = 5;
public function __construct( Container $container, private TwoFactorAuthModel $twoFactorModel, private UserModel $userModel ) { parent::__construct($container); }
/** * Create the TwoFactorAuth object used by every method. */ private function createTwoFactorAuth(): TwoFactorAuth { // TODO: Create an SVG QR code provider and a TwoFactorAuth instance // with your store's name as the issuer. }
/** * Display the QR code to enable 2FA (GET /2fa/setup). */ public function showSetup(Request $request, Response $response, array $args): Response { // TODO: 1. If the user already has 2FA enabled, set an error flash message // using the FlashMessage helper class and redirect to 'user.dashboard'.
// TODO: 2. Reuse the secret saved in the session under '2fa_setup_secret'. // If there is none, create a new secret and save it there.
// TODO: 3. Generate the QR code data URI, using the user's email as the label.
// TODO: 4. Render 'auth/2fa-setup.php' with 'title', 'qrCodeDataUri', and 'secret'. }
/** * Check the first code and enable 2FA (POST /2fa/setup). */ public function enable(Request $request, Response $response, array $args): Response { // TODO: 1. Read the setup secret from the session. If it is missing, // set an error flash message and redirect to '2fa.setup'.
// TODO: 2. If the submitted code is not valid for that secret, set an // error flash message and redirect to '2fa.setup'.
// TODO: 3. Save the secret in the database, remove it from the session, // set a success flash message, and redirect to 'user.dashboard'. }
/** * Display the code form during login (GET /2fa/verify). */ public function showVerify(Request $request, Response $response, array $args): Response { // TODO: If there is no pending login ('2fa_pending_user_id' in the session), // redirect to 'auth.login'. Otherwise, render 'auth/2fa-verify.php'. }
/** * Check the code and complete the login (POST /2fa/verify). */ public function verify(Request $request, Response $response, array $args): Response { // TODO: 1. Read the pending user ID from the session. If there is none, // redirect to 'auth.login'.
// TODO: 2. If the submitted code is not valid for the user's stored secret: // - add 1 to the '2fa_attempts' counter in the session // - after MAX_ATTEMPTS failures, cancel the pending login (see the // hints), set an error flash message, and redirect to 'auth.login' // - otherwise, set an error flash message and redirect to '2fa.verify'
// TODO: 3. Otherwise, complete the login (see How the Login Works), and // redirect by role as in authenticate(). }
/** * Display the password confirmation form (GET /2fa/disable). */ public function showDisable(Request $request, Response $response, array $args): Response { // TODO: Render 'auth/2fa-disable.php' with the title 'Disable 2FA'. }
/** * Disable 2FA after confirming the password (POST /2fa/disable). */ public function disable(Request $request, Response $response, array $args): Response { // TODO: 1. Look up the logged-in user. If the submitted password does not // match their password hash, set an error flash message and // redirect to '2fa.disable.show'.
// TODO: 2. Disable 2FA, set a success flash message, and redirect to 'user.dashboard'. }}- Implement the TODOs
- Save the file
Hints:
- Every wrong code or password redirects back with a flash message, like the failed login in Lab 9. The code is never kept: the user types a fresh one.
showSetup()reuses the secret from the session so that refreshing the page, or entering a wrong code, keeps the QR code the user has already scanned.- Cancel a pending login the same way your Lab 9
logout()method ends a session, so the flash message survives. verifyCode()accepts the current code and, by default, the codes of the 30-second periods just before and after it, so a code that changes while the user types still works.
Step 6: Update the Login
Section titled “Step 6: Update the Login”Objective: Send users who have 2FA enabled to the code form instead of logging them in.
Instructions:
- Open
app/Controllers/AuthController.php - Import
App\Domain\Models\TwoFactorAuthModeland add it to the constructor asprivate TwoFactorAuthModel $twoFactorModel - In
authenticate(), after the credentials are verified and before the call toAuthSession::login(), add:
// TODO: If the user has 2FA enabled, start a pending login instead of logging// the user in, and send them to the code form (see How the Login Works).- Update the
dashboard()method so that it also passes ahas2FAkey (trueorfalse) to the view, telling it whether the logged-in user has 2FA enabled - Save the file
Step 7: Create the Views
Section titled “Step 7: Create the Views”Objective: Create the pages for enabling, verifying, and disabling 2FA.
Step 7.1: The Setup View
Section titled “Step 7.1: The Setup View”Create app/Views/auth/2fa-setup.php:
<?php
use App\Helpers\ViewHelper;
ViewHelper::loadHeader($title);?>
<div class="mx-auto" style="max-width: 500px;"> <h1>Enable Two-Factor Authentication</h1>
<ol> <li>Install Google Authenticator, Microsoft Authenticator, or Authy on your smartphone</li> <li>Scan the QR code below with the app</li> <li>Enter the 6-digit code from the app</li> </ol>
<div class="text-center my-4 p-4 bg-white"> <img src="<?= hs($qrCodeDataUri) ?>" alt="QR code for 2FA setup"> </div>
<div class="bg-light p-3 my-4"> <p><strong>Can't scan?</strong> Enter this code manually:</p> <code style="font-size: 1.2em; letter-spacing: 2px;"><?= hs($secret) ?></code> </div>
<form method="POST" action="<?= APP_BASE_URL ?>/2fa/setup"> <div class="mb-3"> <label for="code" class="form-label">Verification Code:</label> <input type="text" id="code" name="code" class="form-control text-center" inputmode="numeric" pattern="[0-9]{6}" maxlength="6" required autofocus autocomplete="one-time-code" placeholder="000000" style="font-size: 1.5em; letter-spacing: 5px;"> </div>
<button type="submit" class="btn btn-primary">Verify and Enable 2FA</button> <a href="<?= APP_BASE_URL ?>/dashboard" class="btn btn-secondary">Cancel</a> </form></div>
<?php ViewHelper::loadFooter(); ?>Step 7.2: The Verification View
Section titled “Step 7.2: The Verification View”Create app/Views/auth/2fa-verify.php:
<?php
use App\Helpers\ViewHelper;
ViewHelper::loadHeader($title);?>
<div class="mx-auto" style="max-width: 400px;"> <h1>Two-Factor Verification</h1> <p>Enter the 6-digit code from your authenticator app.</p>
<form method="POST" action="<?= APP_BASE_URL ?>/2fa/verify"> <div class="mb-3"> <label for="code" class="form-label">Verification Code:</label> <input type="text" id="code" name="code" class="form-control text-center" inputmode="numeric" pattern="[0-9]{6}" maxlength="6" required autofocus autocomplete="one-time-code" placeholder="000000" style="font-size: 2em; letter-spacing: 10px;"> </div>
<button type="submit" class="btn btn-primary w-100">Verify</button> </form>
<form method="POST" action="<?= APP_BASE_URL ?>/logout" class="mt-4 text-center"> <button type="submit" class="btn btn-link">Cancel</button> </form></div>
<?php ViewHelper::loadFooter(); ?>The “Cancel” button submits to the logout route from Lab 9, which clears the pending login.
Step 7.3: The Disable View
Section titled “Step 7.3: The Disable View”Create app/Views/auth/2fa-disable.php:
<?php
use App\Helpers\ViewHelper;
ViewHelper::loadHeader($title);?>
<div class="mx-auto" style="max-width: 400px;"> <h1>Disable Two-Factor Authentication</h1> <p>Enter your password to confirm.</p>
<form method="POST" action="<?= APP_BASE_URL ?>/2fa/disable"> <div class="mb-3"> <label for="password" class="form-label">Password:</label> <input type="password" id="password" name="password" class="form-control" required> </div>
<button type="submit" class="btn btn-danger">Disable 2FA</button> <a href="<?= APP_BASE_URL ?>/dashboard" class="btn btn-secondary">Cancel</a> </form></div>
<?php ViewHelper::loadFooter(); ?>Step 7.4: Add 2FA to the Dashboard
Section titled “Step 7.4: Add 2FA to the Dashboard”Open app/Views/user/dashboard.php from Lab 9 and add the following card below the existing content:
<div class="card mt-4"> <div class="card-body"> <h5 class="card-title">Two-Factor Authentication</h5>
<?php if ($has2FA): ?> <p class="text-success">2FA is enabled. Your account is protected with a second factor.</p> <a href="<?= APP_BASE_URL ?>/2fa/disable" class="btn btn-outline-danger">Disable 2FA</a> <?php else: ?> <p class="text-warning">2FA is disabled. Enable it to protect your account even if your password is stolen.</p> <a href="<?= APP_BASE_URL ?>/2fa/setup" class="btn btn-primary">Enable 2FA</a> <?php endif; ?> </div></div>Error and success messages are displayed by the flash messages in the public header, so none of these views needs its own error block.
Step 8: Register the Routes
Section titled “Step 8: Register the Routes”Objective: Map the 2FA URLs to the TwoFactorController.
Instructions:
- Open
app/Routes/web-routes.phpand adduse App\Controllers\TwoFactorController;at the top - Register the following routes, outside the
/admingroup:
| Method | Path | Controller Method | Route Name | Middleware |
|---|---|---|---|---|
| GET | /2fa/setup | showSetup | 2fa.setup | AuthMiddleware |
| POST | /2fa/setup | enable | 2fa.enable | AuthMiddleware |
| GET | /2fa/verify | showVerify | 2fa.verify | None |
| POST | /2fa/verify | verify | 2fa.verify.post | None |
| GET | /2fa/disable | showDisable | 2fa.disable.show | AuthMiddleware |
| POST | /2fa/disable | disable | 2fa.disable | AuthMiddleware |
- Save the file
The verification routes have no middleware because the user is not logged in yet. Instead, showVerify() and verify() check for a pending login themselves.
Step 9: Test Your 2FA
Section titled “Step 9: Test Your 2FA”- Enable 2FA: Log in, click “Enable 2FA” on the dashboard, and scan the QR code. Refresh the page: the QR code and the secret should stay the same.
- Wrong setup code: Enter
000000. You should see an error, and the same QR code. - Correct setup code: Enter the code from the app. The dashboard should say that 2FA is enabled.
- Login with 2FA: Log out and log in with your password. You should land on the code form, not the dashboard.
- Pending login is not a login: While on the code form, visit
/dashboarddirectly.AuthMiddlewareshould send you to the login page. - Correct code: Log in again and enter the code from the app. You should reach the dashboard.
- Too many attempts: Log out, log in, and enter 5 wrong codes. You should be back on the login page with an error message.
- Disable 2FA: Click “Disable 2FA”, enter a wrong password (error), then the correct password. Log out and in: no code should be asked.
- Enable again: Enable 2FA a second time. It should work without errors.
Verification Checklist
Section titled “Verification Checklist”Before submitting your lab, verify the following:
- The QR code is generated in SVG format and stays the same when the setup page is refreshed
- Enabling, disabling, and enabling 2FA again works
- With 2FA enabled, a correct password alone does not log the user in
- Protected pages redirect to the login page while the code has not been entered
- The session ID is regenerated when the login completes
- Five wrong codes cancel the pending login and show an error
- Disabling 2FA requires the correct password
Optional Extension A: Remember This Device
Section titled “Optional Extension A: Remember This Device”Objective: Let users skip the code on a device they trust, for 30 days.
When the user checks “Trust this device”, the server creates a random token, stores its hash in the database, and stores the token itself in a cookie. On the next login, if the cookie’s token matches a valid hash for that user, the code is not asked.
A.1: Create the trusted_devices Table
Section titled “A.1: Create the trusted_devices Table”CREATE TABLE IF NOT EXISTS trusted_devices ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, token_hash CHAR(64) UNIQUE NOT NULL, device_name VARCHAR(100), ip_address VARCHAR(45), last_used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;The table stores hash('sha256', $token), never the token itself. If the database leaks, the hashes cannot be used as cookies.
A.2: Create the TrustedDeviceModel
Section titled “A.2: Create the TrustedDeviceModel”Create app/Domain/Models/TrustedDeviceModel.php with a constructor like TwoFactorAuthModel and the following methods. Every method works on the trusted_devices table:
| Method | What It Does |
|---|---|
create(int $userId, string $tokenHash, array $deviceInfo): void | Insert a row; $deviceInfo holds device_name, ip_address, and expires_at |
isValid(string $tokenHash, int $userId): bool | Return true if a row with this hash belongs to the user and has not expired |
updateLastUsed(string $tokenHash): void | Set last_used_at to the current time |
revokeAll(int $userId): void | Delete every trusted device of the user |
A.3: Trust the Device After a Correct Code
Section titled “A.3: Trust the Device After a Correct Code”- Add a checkbox to the form in
2fa-verify.php, above the Verify button:
<div class="form-check mb-3"> <input type="checkbox" class="form-check-input" id="trust_device" name="trust_device" value="1"> <label class="form-check-label" for="trust_device">Trust this device for 30 days</label></div>- Inject
TrustedDeviceModelintoTwoFactorController - In
verify(), after a correct code and before redirecting, if the checkbox was checked:- generate a token with
bin2hex(random_bytes(32)) - save
hash('sha256', $token)with the device name, the IP address, and an expiry date 30 days from now - set the cookie with the options below
- generate a token with
setcookie('trusted_device', $token, [ 'expires' => time() + 30 * 24 * 60 * 60, 'path' => '/' . APP_ROOT_DIR_NAME, 'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', 'httponly' => true, 'samesite' => 'Strict',]);- Add the following
getDeviceName()method to the controller, and write agetClientIp(Request $request): stringmethod that returns the client’s IP address from the request’s server parameters (see the explanation below the code):
private function getDeviceName(Request $request): string{ $userAgent = $request->getHeaderLine('User-Agent');
if (stripos($userAgent, 'iPhone') !== false) return 'iPhone'; if (stripos($userAgent, 'Android') !== false) return 'Android'; if (stripos($userAgent, 'Windows') !== false) return 'Windows PC'; if (stripos($userAgent, 'Mac') !== false) return 'Mac'; if (stripos($userAgent, 'Linux') !== false) return 'Linux PC';
return 'Unknown Device';}getClientIp() must read REMOTE_ADDR, the address of the computer that actually connected, and return '0.0.0.0' if it is missing. Do not read the X-Forwarded-For header: any client can send it with a fake address. It is only trustworthy behind a proxy that you control and that sets it.
A.4: Skip the Code on a Trusted Device
Section titled “A.4: Skip the Code on a Trusted Device”In AuthController::authenticate(), inside the “2FA enabled” branch and before redirecting to 2fa.verify:
- Inject
TrustedDeviceModelintoAuthController - Read the
trusted_devicecookie with$request->getCookieParams() - If it is present and
isValid()returns true for its hash and this user: updatelast_used_at, log the user in withAuthSession::login(), and redirect by role - If it is present but not valid, delete it by setting it again with the same
pathand anexpiresvalue in the past
The cookie must be deleted with the same path it was created with; otherwise, the browser keeps it.
A.5: Revoke Devices When 2FA Is Disabled
Section titled “A.5: Revoke Devices When 2FA Is Disabled”In TwoFactorController::disable(), call revokeAll() for the user and delete the cookie. A device trusted while 2FA was enabled must not stay trusted after it is enabled again.
A.6: Test
Section titled “A.6: Test”Log in with 2FA, check “Trust this device”, and enter the code. Log out and in: the code should not be asked. In a private browser window, log in again: the code should be asked. Disable 2FA, enable it again, and log in from the first browser: the code should be asked again.
Optional Extension B: Require 2FA for Administrators
Section titled “Optional Extension B: Require 2FA for Administrators”Objective: Prevent administrators from using the admin panel until they have enabled 2FA.
Instructions:
- Open
app/Middleware/AdminAuthMiddleware.phpfrom Lab 9 - Add
private TwoFactorAuthModel $twoFactorModelto the constructor, next to the response factory, and importApp\Domain\Models\TwoFactorAuthModel - In
process(), after confirming that the user is an admin, add:
// TODO: If the admin does not have 2FA enabled, set the warning flash message// "Admin accounts require Two-Factor Authentication. Please enable 2FA to continue."// and redirect to '2fa.setup' (same redirect pattern as the other checks).- Save the file
The /2fa/setup routes only use AuthMiddleware, not AdminAuthMiddleware, so the redirect does not loop.