Skip to content

Lab 13: Two-Factor Authentication (2FA)

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.


By completing this lab, you will:

  • Generate a TOTP secret and a QR code with the robthree/twofactorauth library.
  • 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.

Before starting this lab, ensure you have:


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 dashboard

While 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.

StageWhat 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

Objective: Add the TOTP and QR code libraries to your project.

Instructions:

  1. Open a terminal in your project root
  2. Run the following commands:
Install the TOTP and QR Code Libraries
composer require robthree/twofactorauth
composer require bacon/bacon-qr-code

Objective: Store each user’s TOTP secret.

Instructions:

  1. Open phpMyAdmin, select your project database, and click on the “SQL” tab
  2. Execute the following statement:
SQL Statement to Create the two_factor_auth Table
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.


Objective: Create a model that enables, disables, and reads a user’s 2FA secret.

Instructions:

  1. Navigate to your app/Domain/Models/ directory
  2. Create a new file named TwoFactorAuthModel.php
  3. Start from the following class structure:
app/Domain/Models/TwoFactorAuthModel.php
<?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.
}
}
  1. Implement the TODOs
  2. Save the file

Objective: Make the code that logs a user in reusable, because both AuthController and the new TwoFactorController need it.

Instructions:

  1. Open app/Domain/Models/UserModel.php and add a method that finds a user by ID:
app/Domain/Models/UserModel.php
/**
* 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.
}
  1. Navigate to your app/Helpers/ directory and create a file named AuthSession.php:
app/Helpers/AuthSession.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).
}
}
  1. Implement both TODOs
  2. In AuthController::authenticate(), replace the moved code with a call to AuthSession::login($user)
  3. Save the files and check that logging in still works exactly as in Lab 9

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:

  1. Navigate to your app/Controllers/ directory
  2. Create a new file named TwoFactorController.php
  3. Start from the following class structure:
app/Controllers/TwoFactorController.php
<?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'.
}
}
  1. Implement the TODOs
  2. 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.

Objective: Send users who have 2FA enabled to the code form instead of logging them in.

Instructions:

  1. Open app/Controllers/AuthController.php
  2. Import App\Domain\Models\TwoFactorAuthModel and add it to the constructor as private TwoFactorAuthModel $twoFactorModel
  3. In authenticate(), after the credentials are verified and before the call to AuthSession::login(), add:
app/Controllers/AuthController.php
// 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).
  1. Update the dashboard() method so that it also passes a has2FA key (true or false) to the view, telling it whether the logged-in user has 2FA enabled
  2. Save the file

Objective: Create the pages for enabling, verifying, and disabling 2FA.

Create app/Views/auth/2fa-setup.php:

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(); ?>

Create app/Views/auth/2fa-verify.php:

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.

Create app/Views/auth/2fa-disable.php:

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(); ?>

Open app/Views/user/dashboard.php from Lab 9 and add the following card below the existing content:

app/Views/user/dashboard.php
<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.


Objective: Map the 2FA URLs to the TwoFactorController.

Instructions:

  1. Open app/Routes/web-routes.php and add use App\Controllers\TwoFactorController; at the top
  2. Register the following routes, outside the /admin group:
MethodPathController MethodRoute NameMiddleware
GET/2fa/setupshowSetup2fa.setupAuthMiddleware
POST/2fa/setupenable2fa.enableAuthMiddleware
GET/2fa/verifyshowVerify2fa.verifyNone
POST/2fa/verifyverify2fa.verify.postNone
GET/2fa/disableshowDisable2fa.disable.showAuthMiddleware
POST/2fa/disabledisable2fa.disableAuthMiddleware
  1. 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.


  1. 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.
  2. Wrong setup code: Enter 000000. You should see an error, and the same QR code.
  3. Correct setup code: Enter the code from the app. The dashboard should say that 2FA is enabled.
  4. Login with 2FA: Log out and log in with your password. You should land on the code form, not the dashboard.
  5. Pending login is not a login: While on the code form, visit /dashboard directly. AuthMiddleware should send you to the login page.
  6. Correct code: Log in again and enter the code from the app. You should reach the dashboard.
  7. Too many attempts: Log out, log in, and enter 5 wrong codes. You should be back on the login page with an error message.
  8. Disable 2FA: Click “Disable 2FA”, enter a wrong password (error), then the correct password. Log out and in: no code should be asked.
  9. Enable again: Enable 2FA a second time. It should work without errors.

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.

SQL Statement to 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.

Create app/Domain/Models/TrustedDeviceModel.php with a constructor like TwoFactorAuthModel and the following methods. Every method works on the trusted_devices table:

MethodWhat It Does
create(int $userId, string $tokenHash, array $deviceInfo): voidInsert a row; $deviceInfo holds device_name, ip_address, and expires_at
isValid(string $tokenHash, int $userId): boolReturn true if a row with this hash belongs to the user and has not expired
updateLastUsed(string $tokenHash): voidSet last_used_at to the current time
revokeAll(int $userId): voidDelete 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”
  1. 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>
  1. Inject TrustedDeviceModel into TwoFactorController
  2. 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
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',
]);
  1. Add the following getDeviceName() method to the controller, and write a getClientIp(Request $request): string method that returns the client’s IP address from the request’s server parameters (see the explanation below the code):
app/Controllers/TwoFactorController.php
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.

In AuthController::authenticate(), inside the “2FA enabled” branch and before redirecting to 2fa.verify:

  1. Inject TrustedDeviceModel into AuthController
  2. Read the trusted_device cookie with $request->getCookieParams()
  3. If it is present and isValid() returns true for its hash and this user: update last_used_at, log the user in with AuthSession::login(), and redirect by role
  4. If it is present but not valid, delete it by setting it again with the same path and an expires value in the past

The cookie must be deleted with the same path it was created with; otherwise, the browser keeps it.

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.

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:

  1. Open app/Middleware/AdminAuthMiddleware.php from Lab 9
  2. Add private TwoFactorAuthModel $twoFactorModel to the constructor, next to the response factory, and import App\Domain\Models\TwoFactorAuthModel
  3. In process(), after confirming that the user is an admin, add:
app/Middleware/AdminAuthMiddleware.php
// 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).
  1. Save the file

The /2fa/setup routes only use AuthMiddleware, not AdminAuthMiddleware, so the redirect does not loop.