悠悠楠杉
网站页面
在PHP接口开发中,时间戳验证是防止重放攻击(Replay Attack)的常见手段。攻击者可能截获合法请求并重复发送,通过时间戳校验可有效拦截过期请求。本文将分步骤解析如何实现和调试时间戳验证,并提供实战代码示例。
time())。以下是一个简单的时间戳验证类:
class TimestampValidator {
// 允许的时间误差(秒)
const ALLOWED_DELAY = 300;
public static function validate($clientTimestamp) {
$serverTime = time();
$timeDiff = abs($serverTime - $clientTimestamp);
if ($timeDiff > self::ALLOWED_DELAY) {
throw new Exception("请求已过期,请检查时间戳");
}
return true;
}
}
// 使用示例
try {
TimestampValidator::validate($_POST['timestamp']);
echo "验证通过";
} catch (Exception $e) {
http_response_code(400);
echo $e->getMessage();
}时间同步问题
时区差异
date_default_timezone_set('Asia/Shanghai');// Redis存储Nonce示例
$redis = new Redis();
$redis->connect('127.0.0.1');
$nonce = $_POST['nonce'];
if ($redis->exists($nonce)) {
throw new Exception("请求已处理过");
} else {
$redis->setex($nonce, 600, 1); // 10分钟过期
}public function testTimestampValidation() {
$validTimestamp = time();
$this->assertTrue(TimestampValidator::validate($validTimestamp));
$expiredTimestamp = time() - 400;
$this->expectException(Exception::class);
TimestampValidator::validate($expiredTimestamp);
}通过以上方法,开发者可以高效调试时间戳验证逻辑,构建抗重放攻击的健壮接口。