要防止页面 URL 从指定授权页面之外的页面打开,可以采取以下几种方法:
1. 使用 Referer 头检查通过检查 HTTP 请求头中的 Referer 字段来判断请求来源。如果 Referer 不是授权页面的 URL,则拒绝访问。
注意:Referer 头并不是总是可靠的,因为用户可以伪造或禁用 Referer 头,因此这种方法不适用于安全性要求高的场景。
示例(服务器端):
// PHP 示例 $referer = $_SERVER['HTTP_REFERER']; $allowed_referer = 'http://example.com/authorize.php'; if (!isset($referer) || $referer !== $allowed_referer) { header('HTTP/1.0 403 Forbidden'); echo 'Forbidden'; exit; }2. 使用 Token 机制
在授权页面生成一个随机 token,并将其存储在会话(Session)或 Cookie 中。然后在目标页面检查该 token 是否存在且有效。
步骤:
授权页面:
生成一个随机 token 并存储在会话中。将 token 作为参数传递到目标页面的 URL 中。// 授权页面 session_start(); $_SESSION['token'] = bin2hex(random_bytes(16)); $url = 'http://example.com/target.php?token=' . $_SESSION['token']; echo '<a href="' . $url . '">进入目标页面</a>';
目标页面:
检查 URL 中的 token 是否与会话中的 token 匹配。如果匹配,则允许访问;否则,重定向到授权页面或显示错误信息。// 目标页面 session_start(); $token = $_GET['token']; if (!isset($token) || $token !== $_SESSION['token']) { header('Location: http://example.com/authorize.php'); exit; } // 允许访问页面内容3. 使用会话状态检查
在授权页面设置一个会话变量,表示用户已经通过授权。目标页面检查该会话变量是否存在。
步骤:
授权页面:
设置会话变量表示授权通过。// 授权页面 session_start(); $_SESSION['authorized'] = true; header('Location: http://example.com/target.php'); exit;
目标页面:
检查会话变量是否设置。// 目标页面 session_start(); if (!isset($_SESSION['authorized']) || !$_SESSION['authorized']) { header('Location: http://example.com/authorize.php'); exit; } // 允许访问页面内容4. 使用 HTML5 History API
通过 JavaScript 控制页面的导航,防止用户直接输入 URL 访问页面。
步骤:
授权页面:
重定向到目标页面,并在 URL 中添加一个参数表示来源。// 授权页面 window.location.href = 'http://example.com/target.php?from=authorize';
目标页面:
检查 URL 参数,并使用 history.pushState 或 history.replaceState 来移除参数,防止用户直接访问。// 目标页面 if (new URLSearchParams(window.location.search).get('from') !== 'authorize') { // 重定向到授权页面或显示错误信息 window.location.href = 'http://example.com/authorize.php'; } else { // �移除参数,防止用户直接访问 history.replaceState({}, document.title, window.location.pathname); // 允许访问页面内容 }5. 结合服务器端和客户端验证
结合上述方法,同时在服务器端和客户端进行验证,提高安全性。
网友回复