Search code examples
cakephpcakephp-3.x

How to disable CSRF for a plugin?


I developed a CakePHP 3 plugin that has to handle POST requests without a CSRF token.

In the application where I use the plugin I apply the middleware to the root scope.

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

    $routes->applyMiddleware('csrf');
...

How can I disable the middleware for the plugin?

I tried $this->addPlugin(\My\Plugin::class, ['middleware' => false]) but that didn't work.

Or is the Plugin responsible to disable the CSRF middleware?


Solution

  • The problem was that I forgot to load the plugin routes in Application::bootstrap().

    $this->addPlugin(\My\Plugin::class, ['routes' => true]);
    

    According to the cake book routes, bootstrap, middleware and console hooks are disabled by default.