48 lines
1.6 KiB
PHP
48 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class VerifyHxbOtpRelaySignature
|
|
{
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$secret = trim((string) config('hxb_otp.api_secret', ''));
|
|
if ($secret === '') {
|
|
abort(503, '华夏验证码中继未配置。');
|
|
}
|
|
|
|
$timestamp = trim((string) $request->header('X-HXB-Timestamp', ''));
|
|
$nonce = trim((string) $request->header('X-HXB-Nonce', ''));
|
|
$signature = strtolower(trim((string) $request->header('X-HXB-Signature', '')));
|
|
$ttl = max(60, (int) config('hxb_otp.signature_ttl_seconds', 300));
|
|
if (! ctype_digit($timestamp)
|
|
|| abs(time() - (int) $timestamp) > $ttl
|
|
|| ! preg_match('/^[a-f0-9]{16,128}$/', $nonce)
|
|
|| ! preg_match('/^[a-f0-9]{64}$/', $signature)) {
|
|
abort(401, '请求签名无效。');
|
|
}
|
|
|
|
$canonical = implode("\n", [
|
|
strtoupper($request->method()),
|
|
$request->path(),
|
|
$timestamp,
|
|
$nonce,
|
|
hash('sha256', $request->getContent()),
|
|
]);
|
|
$expected = hash_hmac('sha256', $canonical, $secret);
|
|
if (! hash_equals($expected, $signature)) {
|
|
abort(401, '请求签名无效。');
|
|
}
|
|
if (! Cache::add('hxb-otp-signature:' . $nonce, 1, $ttl)) {
|
|
abort(409, '请求已使用。');
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
}
|