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

如何在Slim 3中排除API路由的CSRF中间件校验?

解决Slim3中API路由排除CSRF校验的方案

我来帮你完善这个基于方案2的实现,咱们直接通过重写CsrfMiddleware的processRequest方法,来跳过指定API路由的CSRF校验:

完整的App\Middleware\CsrfMiddleware.php代码

namespace App\Middleware;

class CsrfMiddleware extends \Slim\Csrf\Guard
{
    public function processRequest($request, $response, $next)
    {
        // 定义需要排除CSRF校验的API路由前缀,比如所有/api开头的请求
        $apiRoutePrefix = '/api';
        
        // 获取当前请求的URI路径
        $requestUri = $request->getUri()->getPath();
        
        // 判断当前请求是否属于API路由,是则直接跳过CSRF校验
        if (strpos($requestUri, $apiRoutePrefix) === 0) {
            return $next($request, $response);
        }
        
        // 非API路由,执行父类的标准CSRF校验逻辑
        return parent::processRequest($request, $response, $next);
    }
}

在Slim应用中注册自定义中间件

接下来把原来的Slim\Csrf\Guard中间件替换成咱们这个自定义类,在应用初始化文件(比如public/index.php或config/middleware.php)里修改如下:

// 实例化自定义的CsrfMiddleware
$csrf = new App\Middleware\CsrfMiddleware();

// 注册为全局中间件(也可以按需注册到非API路由组)
$app->add($csrf);

可选:更灵活的排除规则

如果你的API路由规则比较复杂,不想只用前缀判断,可以改成支持多路由模式的版本:

namespace App\Middleware;

class CsrfMiddleware extends \Slim\Csrf\Guard
{
    // 存储需要排除的路由模式集合
    private $excludedRoutes = [];
    
    // 通过构造方法传入自定义排除规则
    public function __construct($excludedRoutes = [])
    {
        parent::__construct();
        $this->excludedRoutes = $excludedRoutes;
    }
    
    public function processRequest($request, $response, $next)
    {
        $requestUri = $request->getUri()->getPath();
        
        // 遍历排除规则,匹配到则跳过校验
        foreach ($this->excludedRoutes as $routePattern) {
            if (fnmatch($routePattern, $requestUri)) {
                return $next($request, $response);
            }
        }
        
        return parent::processRequest($request, $response, $next);
    }
}

注册时就能指定具体的排除路由:

$excludedRoutes = [
    '/api/*',
    '/api/v2/users/*',
    '/api/public/health-check'
];
$csrf = new App\Middleware\CsrfMiddleware($excludedRoutes);
$app->add($csrf);

这样就能精准控制哪些路由不需要CSRF校验,完美适配你的REST API场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:30:33