Cakephp 3.5.6禁用控制器的CSRF中间件

时间:2017-12-08 13:00:00

标签: cakephp cakephp-3.0 csrf middleware

我试图禁用单个控制器(API)的CSRF检查,但我无法找到我能够实现的目标。

3.5.0之前的CSRF组件可以使用以下命令禁用某些请求:

$this->eventManager()->off($this->Csrf);

4 个答案:

答案 0 :(得分:10)

有两种方法可以做到。

将中间件应用于特定的路由范围(甚至路由)

根据您创建的路由,您可以仅将中间件应用于特定范围,例如:

// config/routes.php

use Cake\Http\Middleware\CsrfProtectionMiddleware;

Router::scope('/', function ($routes) {
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));

    $routes->scope('/api', function ($routes) {
        // ...
    });

    $routes->scope('/blog', function ($routes) {
        $routes->applyMiddleware('csrf');
        // ...
    });

    $routes->scope('/cms', function ($routes) {
        $routes->applyMiddleware('csrf');
        // ...
    });
});

这会将CSRF中间件仅应用于blogcms范围内连接的路由。

还可以进一步缩小到路由级别,并在特定路径上应用中间件:

$routes
    ->connect('/blog/:action', ['controller' => 'Blogs'])
    ->setMiddleware(['csrf']);

这会将CSRF中间件仅应用于/blog/*路由。

有条件地手动应用中间件

另一种方法是在适用时手动应用中间件。为了能够做到这一点,您必须创建一个自定义中间件处理程序,以便您可以访问当前请求对象,从中可以提取controller参数,然后您必须< em>在你的处理程序中调用 CSRF中间件,类似于:

// src/Application.php

// ...
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class Application extends BaseApplication
{
    // ...

    public function middleware($middleware)
    {
        $middleware
            // ...
            ->add(new RoutingMiddleware())

            ->add(function (
                ServerRequestInterface $request,
                ResponseInterface $response,
                callable $next
            ) {
                $params = $request->getAttribute('params');
                if ($params['controller'] !== 'Api') {
                    $csrf = new CsrfProtectionMiddleware([
                        'httpOnly' => true
                    ]);

                    // This will invoke the CSRF middleware's `__invoke()` handler,
                    // just like it would when being registered via `add()`.
                    return $csrf($request, $response, $next);
                }

                return $next($request, $response);
            });

        return $middleware;
    }
}

请注意,您必须在路由中间件之后应用自定义中间件,因为这是设置控制器信息的位置。

如果适用,您还可以针对请求网址而不是路由参数进行测试,例如:

if (mb_strpos($request->getUri()->getPath(), '/api/') === false) {
    $csrf = new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]);

    return $csrf($request, $response, $next);
}

这样做时,自定义中间件不会被限制在路由中间件之后放置,理论上你可以把它放在你想要的任何位置。

另见

答案 1 :(得分:1)

我认为在Cake 3.6中,您应该从中间件中删除CsrfProtectionMiddleware:

队列:src / Application.php

final Specification<Job> specification = (root, query, cb) -> {
            query.orderBy(cb.asc(root.get("code"))); 
            query.groupBy(cb.substring(root.get("code"), 1 , (cb.length(root.get("code"))-5) ));
            return cb.and(
                    //...
        };

答案 2 :(得分:0)

在Cakephp 3.8中,我将所有方法实现注释到了\ vendor \ cakephp \ cakephp \ src \ Http \ Middleware \ CsrfProtectionMiddleware.php类中,因此禁用了Csrf中间件:-)

答案 3 :(得分:0)

3.8、3.9

的最新解决方案

首先从 route.php 中删除中间件。

Router::scope('/', function (RouteBuilder $routes) {
    // Register scoped middleware for in scopes.
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));

    /**
     * Apply a middleware to the current route scope.
     * Requires middleware to be registered via `Application::routes()` with `registerMiddleware()`
     */
    $routes->applyMiddleware('csrf');

    //...
}

注释 registerMiddleware applyMiddleware('csrf')

Router::scope('/', function (RouteBuilder $routes) {
    //    // Register scoped middleware for in scopes.
    //    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
    //        'httpOnly' => true
    //    ]));
    //
    //    /**
    //     * Apply a middleware to the current route scope.
    //     * Requires middleware to be registered via `Application::routes()` with `registerMiddleware()`
    //     */
    //    $routes->applyMiddleware('csrf');
//...
}

现在,从 /Application.php 编辑 middleware()函数:

/**
     * Setup the middleware queue your application will use.
     *
     * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
     * @return \Cake\Http\MiddlewareQueue The updated middleware queue.
     */
    public function middleware($middlewareQueue)
    {
       // loading csrf Middleware ---- Add this code Block
        $csrf = new CsrfProtectionMiddleware([
            'httpOnly' => true
        ]);
        $csrf->whitelistCallback(function (ServerRequest $request) {
            // skip controllers
            $skipedControllers = ['MyControllerToSkip', 'MyControllerToSkip2']; // EDIT THIS 
            if(in_array($request->getParam('controller'),$skipedControllers)) {
                return true;
            }
            // skip debugkit
            if($request->getParam('plugin') == 'DebugKit') {
                return true;
            }
            return $request;
        });
        // end codeblock to add, you have to add a other code line below ->add(new RoutingMiddleware($this)) -------

        $middlewareQueue
            // Catch any exceptions in the lower layers,
            // and make an error page/response
            ->add(new ErrorHandlerMiddleware(null, Configure::read('Error')))

            // Handle plugin/theme assets like CakePHP normally does.
            ->add(new AssetMiddleware([
                'cacheTime' => Configure::read('Asset.cacheTime')
            ]))

            // Add routing middleware.
            // If you have a large number of routes connected, turning on routes
            // caching in production could improve performance. For that when
            // creating the middleware instance specify the cache config name by
            // using it's second constructor argument:
            // `new RoutingMiddleware($this, '_cake_routes_')`
            ->add(new RoutingMiddleware($this))
            ->add($csrf);   // <---- Don't forget to add this !  

        return $middlewareQueue;
    }

不要忘记在-> add(新的RoutingMiddleware($ this))之后的最终-> add($ csrf);