「永久登入」本質是跨 Session 持久化認證。主要風險:
CREATE TABLE `persistent_logins` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` INT UNSIGNED NOT NULL,
`selector` CHAR(32) NOT NULL COMMENT '16 bytes hex, 公開查詢用',
`validator_hash` CHAR(64) NOT NULL COMMENT 'sha256(validator), 驗證用',
`expires_at` DATETIME NOT NULL,
`user_agent` VARCHAR(255) DEFAULT '',
`ip_address` VARCHAR(45) DEFAULT '',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
`last_used_at` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_selector` (`selector`),
KEY `idx_user_expires` (`user_id`, `expires_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='持久化登入 Token';
<?php
class PersistentLogin {
private PDO $pdo;
private int $tokenLifetime; // 秒
private string $cookieName;
private array $cookieOptions;
public function __construct(PDO $pdo, array $config = []) {
$this->pdo = $pdo;
$this->tokenLifetime = $config['lifetime'] ?? 30 * 86400; // 30 天
$this->cookieName = $config['cookie_name'] ?? 'persistent_login';
$this->cookieOptions = [
'expires' => time() + $this->tokenLifetime,
'path' => $config['cookie_path'] ?? '/',
'domain' => $config['cookie_domain'] ?? '',
'secure' => $config['secure'] ?? true,
'httponly' => true,
'samesite' => $config['samesite'] ?? 'Lax'
];
}
/**
* 登入成功後簽發 Token
*/
public function issueToken(int $userId, array $context = []): string {
$selector = random_bytes(16);
$validator = random_bytes(32);
$expiresAt = (new DateTime())->modify("+{$this->tokenLifetime} seconds")->format('Y-m-d H:i:s');
$stmt = $this->pdo->prepare("
INSERT INTO persistent_logins (user_id, selector, validator_hash, expires_at, user_agent, ip_address)
VALUES (?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$userId,
bin2hex($selector),
hash('sha256', $validator),
$expiresAt,
$context['user_agent'] ?? ($_SERVER['HTTP_USER_AGENT'] ?? ''),
$context['ip'] ?? ($_SERVER['REMOTE_ADDR'] ?? '')
]);
$cookieValue = base64_encode($selector . ':' . $validator);
setcookie($this->cookieName, $cookieValue, $this->cookieOptions);
return $cookieValue;
}
/**
* 從 Cookie 驗證並重建 Session
* @return int|false 用戶 ID 或 false
*/
public function validateAndRefresh(): int|false {
if (empty($_COOKIE[$this->cookieName])) return false;
$cookieValue = @base64_decode($_COOKIE[$this->cookieName]);
if (!$cookieValue || strpos($cookieValue, ':') === false) {
$this->clearCookie();
return false;
}
list($selectorHex, $validator) = explode(':', $cookieValue, 2);
$stmt = $this->pdo->prepare("
SELECT user_id, validator_hash, expires_at, user_agent, ip_address
FROM persistent_logins WHERE selector = ?
");
$stmt->execute([$selectorHex]);
$token = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$token) {
$this->clearCookie();
return false;
}
// 過期檢查
if (strtotime($token['expires_at']) < time()) {
$this->revokeToken($selectorHex);
$this->clearCookie();
return false;
}
// 驗證 Validator (恆時比較)
if (!hash_equals($token['validator_hash'], hash('sha256', $validator))) {
// 驗證失敗:可疑活動,撤銷該用戶所有 Token
$this->revokeAllUserTokens($token['user_id']);
$this->clearCookie();
// 記錄安全事件
error_log("SECURITY: Invalid validator for user {$token['user_id']} from IP {$_SERVER['REMOTE_ADDR']}");
return false;
}
// 可選:設備指紋檢查
if ($this->isSuspiciousContext($token)) {
// 要求二次驗證,不自動登入
$this->clearCookie();
return false;
}
// 成功:滑動過期更新
$newExpire = (new DateTime())->modify("+{$this->tokenLifetime} seconds")->format('Y-m-d H:i:s');
$this->pdo->prepare("UPDATE persistent_logins SET expires_at = ?, last_used_at = NOW() WHERE selector = ?")
->execute([$newExpire, $selectorHex]);
// 更新 Cookie 過期時間
$this->cookieOptions['expires'] = time() + $this->tokenLifetime;
setcookie($this->cookieName, $_COOKIE[$this->cookieName], $this->cookieOptions);
return (int)$token['user_id'];
}
private function isSuspiciousContext(array $token): bool {
$currentUA = $_SERVER['HTTP_USER_AGENT'] ?? '';
$currentIP = $_SERVER['REMOTE_ADDR'] ?? '';
// 簡單策略:UA 完全不匹配 或 IP 段變化 (首段不同)
if ($token['user_agent'] && $token['user_agent'] !== $currentUA) return true;
if ($token['ip_address'] && explode('.', $token['ip_address'])[0] !== explode('.', $currentIP)[0]) return true;
return false;
}
/**
* 登出:撤銷當前 Token
*/
public function logout(int $userId = null, string $selectorHex = null): void {
if ($selectorHex) {
$this->revokeToken($selectorHex);
} elseif ($userId) {
$this->revokeAllUserTokens($userId);
}
$this->clearCookie();
}
private function revokeToken(string $selectorHex): void {
$this->pdo->prepare("DELETE FROM persistent_logins WHERE selector = ?")->execute([$selectorHex]);
}
private function revokeAllUserTokens(int $userId): void {
$this->pdo->prepare("DELETE FROM persistent_logins WHERE user_id = ?")->execute([$userId]);
}
private function clearCookie(): void {
setcookie($this->cookieName, '', time() - 3600, $this->cookieOptions);
}
/**
* 獲取用戶活躍 Token 列表 (用戶管理介面)
*/
public function getUserTokens(int $userId): array {
$stmt = $this->pdo->prepare("
SELECT selector, expires_at, user_agent, ip_address, created_at, last_used_at
FROM persistent_logins WHERE user_id = ? ORDER BY created_at DESC
");
$stmt->execute([$userId]);
return $stmt->fetchAll();
}
/**
* 清理過期 Token (定時任務執行)
*/
public function cleanupExpired(): int {
$stmt = $this->pdo->prepare("DELETE FROM persistent_logins WHERE expires_at < NOW()");
$stmt->execute();
return $stmt->rowCount();
}
}
// 使用範例
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'user', 'pass', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$persistentLogin = new PersistentLogin($pdo, [
'lifetime' => 30 * 86400,
'secure' => true, // 僅 HTTPS
'samesite' => 'Lax'
]);
// 1. 登入頁面處理
if ($_POST['login']) {
// ... 驗證帳密成功 ...
$userId = 123;
$_SESSION['user_id'] = $userId;
if (!empty($_POST['remember'])) {
$persistentLogin->issueToken($userId);
}
header('Location: /dashboard');
exit;
}
// 2. 所有受保護頁面頂部
$userId = $_SESSION['user_id'] ?? $persistentLogin->validateAndRefresh();
if (!$userId) {
header('Location: /login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
exit;
}
// $userId 可用
// 3. 登出
if ($_GET['action'] === 'logout') {
$persistentLogin->logout($userId);
session_destroy();
header('Location: /login');
exit;
}
// 每次驗證成功後,撤銷舊 Token 並簽發新 Token
public function validateAndRotate(): int|false {
$userId = $this->validateAndRefresh(); // 先驗證
if ($userId) {
// 解析當前 selector
$cookieValue = @base64_decode($_COOKIE[$this->cookieName]);
list($selectorHex) = explode(':', $cookieValue, 2);
// 撤銷舊的
$this->revokeToken($selectorHex);
// 簽發新的
$this->issueToken($userId);
}
return $userId;
}
if ($this->isSuspiciousContext($token)) {
// 發送郵件/簡訊/推播通知用戶
$this->notifySecurityAlert($token['user_id'], [
'ip' => $_SERVER['REMOTE_ADDR'],
'ua' => $_SERVER['HTTP_USER_AGENT'],
'time' => date('Y-m-d H:i:s')
]);
return false; // 強制重新登入
}
// 敏感操作檢查
function requireFreshAuth(): bool {
// 判斷 Session 是否由 Persistent Login 建立
if (!empty($_SESSION['via_persistent_login'])) {
// 要求輸入密碼/TOTP/簡訊碼
return verify2fa();
}
return true; // 正常 Session 直接通過
}
setcookie($name, $value, [
'expires' => time() + 30*86400,
'path' => '/',
'domain' => '.example.com', // 子域共享時設定
'secure' => true, // 僅 HTTPS (生產必須)
'httponly' => true, // 防 XSS 竊取
'samesite' => 'Lax' // 平衡安全與體驗 (Strict 可能阻擋外部鏈接跳轉)
]);
安全的永久登入實現核心:
參考標準:OWASP Authentication Cheat Sheet、NIST SP 800-63B、RFC 6265bis (Cookie 標準)。