萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 安全登入系統設計:Cookie Token 驗證與 Email 確認機制

設計一個安全、可擴展、不依賴資料庫 Session 儲存的 PHP 登入系統。核心採用 HMAC 風格的 Cookie Token 驗證,結合 Email 確認流程,實現無狀態認證與帳號管理。

核心設計理念

  • 無狀態認證: 不在資料庫儲存 Session,驗證邏輯在 Web 伺服器端運算,支援水平擴展
  • 雙 Cookie 驗證: user_name + id_hash,後者為 HMAC(username, secret_key)
  • 單向雜湊不可逆: 使用 md5()(教學用)或 hash_hmac('sha256', ...)(生產環境)
  • Email 確認機制: 修改 Email 時發送含 Token 連結,點擊驗證後才生效

核心程式庫 auth.php

<?php
// 密鑰:必須極度機密、足夠長、隨機產生、僅存放於伺服器端程式碼
define('AUTH_SECRET_KEY', 'your_very_long_random_secret_key_here_min_32_chars');

// 全域登入狀態快取
$LOGGED_IN = null;

/**
 * 檢查使用者是否已登入
 * @return bool
 */
function user_is_logged_in(): bool {
    global $LOGGED_IN, $COOKIE;
    
    // 已檢查過直接回傳快取結果
    if ($LOGGED_IN !== null) {
        return $LOGGED_IN;
    }
    
    // 取得 Cookie(PHP 5.4+ 使用 $_COOKIE)
    $user_name = $_COOKIE['user_name'] ?? '';
    $id_hash   = $_COOKIE['id_hash'] ?? '';
    
    // 雙 Cookie 必須同時存在
    if (!$user_name || !$id_hash) {
        return $LOGGED_IN = false;
    }
    
    // 重新計算預期雜湊值
    $expected_hash = hash_hmac('sha256', strtolower($user_name), AUTH_SECRET_KEY);
    
    // 使用 hash_equals 防止時序攻擊
    if (hash_equals($expected_hash, $id_hash)) {
        return $LOGGED_IN = true;
    }
    
    return $LOGGED_IN = false;
}

/**
 * 登入成功後設定認證 Cookie
 * @param string $username
 * @param int $expire 秒數,預設 30 天
 */
function user_set_tokens(string $username, int $expire = 2592000): void {
    $username = strtolower(trim($username));
    $id_hash = hash_hmac('sha256', $username, AUTH_SECRET_KEY);
    
    $cookie_params = [
        'expires' => time() + $expire,
        'path'    => '/',
        'domain'  => '',           // 當前域名
        'secure'  => isset($_SERVER['HTTPS']), // 僅 HTTPS 傳送
        'httponly' => true,        // 防 XSS 竊取
        'samesite' => 'Lax',       // CSRF 防護
    ];
    
    setcookie('user_name', $username, $cookie_params);
    setcookie('id_hash', $id_hash, $cookie_params);
}

/**
 * 登出:清除 Cookie
 */
function user_logout(): void {
    global $LOGGED_IN;
    $params = ['expires' => time() - 3600, 'path' => '/', 'httponly' => true, 'samesite' => 'Lax'];
    setcookie('user_name', '', $params);
    setcookie('id_hash', '', $params);
    $LOGGED_IN = false;
}

/**
 * 變更 Email 流程:發送確認信
 * @param string $current_password 目前密碼(驗證身分)
 * @param string $new_email 新 Email
 * @param string $username 使用者名稱
 */
function user_request_email_change(string $current_password, string $new_email, string $username): bool {
    global $pdo; // 假設已建立 PDO 連線
    
    // 基本驗證
    if (!filter_var($new_email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Email 格式無效');
    }
    
    // 驗證目前密碼
    $stmt = $pdo->prepare('SELECT password_hash FROM users WHERE username = ?');
    $stmt->execute([strtolower($username)]);
    $user = $stmt->fetch();
    
    if (!$user || !password_verify($current_password, $user['password_hash'])) {
        throw new Exception('目前密碼錯誤');
    }
    
    // 產生確認 Token:HMAC(new_email, secret)
    $confirm_hash = hash_hmac('sha256', strtolower($new_email), AUTH_SECRET_KEY);
    
    // 寫入資料庫:暫存新 email 與確認碼,尚未生效
    $stmt = $pdo->prepare('UPDATE users SET pending_email = ?, confirm_hash = ? WHERE username = ?');
    $stmt->execute([strtolower($new_email), $confirm_hash, strtolower($username)]);
    
    // 發送確認信
    return user_send_confirm_email($new_email, $confirm_hash);
}

/**
 * 驗證 Email 確認連結
 * @param string $hash 確認碼
 * @param string $email Email
 */
function user_confirm_email(string $hash, string $email): bool {
    global $pdo;
    
    // 驗證 hash 正確性(防竄改)
    $expected = hash_hmac('sha256', strtolower($email), AUTH_SECRET_KEY);
    if (!hash_equals($expected, $hash)) {
        throw new Exception('驗證碼無效或已被竄改');
    }
    
    // 查詢待確認記錄
    $stmt = $pdo->prepare('SELECT username FROM users WHERE confirm_hash = ? AND pending_email = ?');
    $stmt->execute([$hash, strtolower($email)]);
    $user = $stmt->fetch();
    
    if (!$user) {
        throw new Exception('找不到對應的待確認帳號');
    }
    
    // 正式更新 email、清除確認碼、標記已驗證
    $stmt = $pdo->prepare('UPDATE users SET email = ?, pending_email = NULL, confirm_hash = NULL, is_confirmed = 1 WHERE username = ?');
    $stmt->execute([strtolower($email), $user['username']]);
    
    // 自動登入
    user_set_tokens($user['username']);
    
    return true;
}

/**
 * 發送確認 Email
 */
function user_send_confirm_email(string $email, string $hash): void {
    $confirm_url = "https://{$_SERVER['HTTP_HOST']}/confirm.php?hash={$hash}&email=" . urlencode($email);
    $message = "感謝註冊!請點擊以下連結確認您的 Email:\n\n{$confirm_url}\n\n若非您本人操作,請忽略此信。";
    
    $headers = "From: noreply@example.com\r\n"
             . "Content-Type: text/plain; charset=UTF-8\r\n"
             . "X-Mailer: PHP/" . phpversion();
    
    mail($email, '帳號 Email 確認', $message, $headers);
    // 生產環境建議使用 PHPMailer + SMTP
}

使用範例

登入頁 login.php

<?php
require 'auth.php';
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = strtolower(trim($_POST['username'] ?? ''));
    $password = $_POST['password'] ?? '';
    
    $stmt = $pdo->prepare('SELECT password_hash FROM users WHERE username = ?');
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password_hash'])) {
        user_set_tokens($username);
        header('Location: dashboard.php');
        exit;
    }
    $error = '帳號或密碼錯誤';
}
?>
<form method="post">
    <input name="username" required>
    <input name="password" type="password" required>
    <button>登入</button>
</form>

受保護頁面 dashboard.php

<?php
require 'auth.php';

if (!user_is_logged_in()) {
    header('Location: login.php');
    exit;
}

// 取得當前使用者
$username = $_COOKIE['user_name'] ?? '';
?>
<h1>歡迎,<?= htmlspecialchars($username) ?></h1>
<a href="logout.php">登出</a>

確認頁 confirm.php

<?php
require 'auth.php';

try {
    $hash  = $_GET['hash'] ?? '';
    $email = $_GET['email'] ?? '';
    user_confirm_email($hash, $email);
    echo 'Email 確認成功,已自動登入!';
    header('Refresh: 2; url=dashboard.php');
} catch (Exception $e) {
    echo '確認失敗:' . htmlspecialchars($e->getMessage());
}

安全性強化建議

項目建議
雜湊演算法生產環境用 hash_hmac('sha256', ...),棄用 MD5
密鑰管理存放於環境變數或金鑰管理系統,勿提交至版控
Cookie 旗標Secure、HttpOnly、SameSite=Lax/Strict
時序攻擊防護比對雜湊用 hash_equals()
Token 過期Cookie 設定合理過期時間,敏感操作要求重新驗證密碼
HTTPS 強制全站 HTTPS,Cookie Secure 旗標生效
資料庫索引confirm_hash、pending_email 加索引

擴展性優勢

  • 驗證邏輯在 Web 層運算,不佔用資料庫連線,支援無限水平擴展
  • 多台 Web Server 共用同一 AUTH_SECRET_KEY 即可共享登入狀態
  • 資料庫瓶頸僅在「查詢使用者資料」而非「驗證 Session」

此架構結合現代最佳實踐(HMAC、hash_equals、Secure Cookie),提供生產級的安全登入基礎。

copyright © 萬盛學電腦網 all rights reserved