Laravel (PHP)
在 Laravel 应用中集成 ProxyTracer 非常便捷。通过创建标准 HTTP 中间件,您可以全局保护整个应用,或按需精准作用于 /login、/checkout 等敏感路由。
中间件实现
Laravel 原生 $request->ip() 方法能自动处理反向代理 IP 提取(前提是已正确配置 TrustProxies 中间件)。我们使用 Laravel 原生 Http 门面发起快速查询,并在命中威胁时丢弃请求。
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
class ProxyTracerMiddleware
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): Response
{
// 1. 提取 IP(Laravel 会自动安全地处理反向代理)
$ip = $request->ip();
// 跳过本地开发环境 IP
if (!in_array($ip, ['127.0.0.1', '::1'])) {
try {
// 2. 查询 ProxyTracer API(配置严格的 500ms 超时)
$response = Http::withToken(env('PROXYTRACER_API_KEY'))
->timeout(0.5)
->get("https://api.proxytracer.com/v1/check/{$ip}");
if ($response->successful()) {
// 3. 若检测到代理,则立即丢弃连接
if ($response->json('proxy') === true) {
return response()->json([
'error' => 'Access Denied: VPN or Proxy detected.'
], 403);
}
}
} catch (\Exception $e) {
// 故障开放(Fail-open):记录错误并放行请求以确保可用性
Log::warning("ProxyTracer validation failed: " . $e->getMessage());
}
}
// 4. 流量正常,继续放行至控制器
return $next($request);
}
}配置说明:
使用 Artisan 命令生成中间件:php artisan make:middleware ProxyTracerMiddleware。
若需全局生效,请将中间件追加至应用程序的中间件堆栈中。
-
Laravel 11 及以上:在
bootstrap/app.php文件的$middleware->append()中注册。 -
Laravel 10 及以下:在
app/Http/Kernel.php文件的$middleware数组中添加该中间件。
最后更新于