You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Laravel中间件允许cURL访问(基于Jessengers/Agent)

解决Laravel中BotMiddleware允许cURL请求通过的问题

问题分析

当前中间件无法识别cURL请求,核心原因是默认情况下cURL发送的User-Agent头格式为curl/{版本号}(例如curl/7.81.0),而非单纯的curl,因此严格相等的判断条件无法匹配。

修正方案

1. 调整cURL请求识别逻辑

修改isCurlRequest方法,通过检测User-Agent是否包含curl相关标识来识别cURL请求,兼容默认格式和用户自定义的cURL User-Agent。

2. 保留原有逻辑顺序

保持先判断cURL请求直接放行,再校验爬虫拒绝访问的逻辑,确保业务规则清晰。

修改后的完整中间件代码

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;

class BotMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $agent = new Agent();

        // 优先放行cURL请求
        if ($this->isCurlRequest($request)) {
            return $next($request);
        }

        // 拒绝爬虫访问
        if ($agent->isRobot()) {
            return response('Bot detected, access denied', 403);
        }

        return $next($request);
    }

    /**
     * 检测是否为cURL请求
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    private function isCurlRequest(Request $request)
    {
        $userAgent = $request->header('User-Agent');
        
        // 处理User-Agent不存在的情况
        if (!$userAgent) {
            return false;
        }

        // 不区分大小写检测是否包含curl标识
        return stripos($userAgent, 'curl') !== false;
    }
}

补充说明

  • 若需要仅允许默认格式的cURL请求(即curl/开头的User-Agent),可将判断条件改为:
    return str_starts_with(strtolower($userAgent), 'curl/');
    
  • 若你使用自定义cURL User-Agent(例如curl -A "MyCustomCurl"),可添加白名单逻辑:
    $allowedCurlAgents = ['MyCustomCurl', 'curl/7.81.0'];
    return in_array($userAgent, $allowedCurlAgents);
    

内容的提问来源于stack exchange,提问作者Pouya Vaghefi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:22:28