0
votes

Here's what I have

Cakephp 3.7.2; in my routes.php:

<?php

use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;
use Cake\Http\Middleware\CsrfProtectionMiddleware;

Router::defaultRouteClass(DashedRoute::class);

Router::scope('/', function (RouteBuilder $routes) {
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware());
    $routes->applyMiddleware('csrf');
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
    $routes->fallbacks(DashedRoute::class);
});
/*
Router::scope('/api', function ($routes) {
  // connect routes with *no* CSRF protection as that middleware is not active
  // for this routing scope.
});
*/
Router::prefix('api', function ($routes) {
    $routes->prefix('users', function ($routes) {
        $routes->fallbacks(DashedRoute::class);
    });
});

What I'm doing

Make a POST request to /api/users using Postman. The request goes through and I see the correct response. I want to make sure I have the protection enabled for the rest of the site, so I'm expecting one of those Missing CSRF token cookie errors though. Once confirmed, I will uncomment the API route exception.

What I've tried

  • Follow controllers/middleware.html#csrf-middleware and put the registerMiddleware() call into src/Application.php
  • Put some gibberish into the applyMiddleware() call. It complains about not being able to find that middleware, which confirms the function does get called
  • Put $this->loadComponent('Csrf'); into AppController.php. It works and I do get the Missing CSRF token cookie. It does not show me the warning about conflicting components like this page says it should

I'm under impression the middleware was not enabled properly, but it's not obvious to me what exactly is wrong. Please assist

1
I will be able to accept the answer and close the question in two days. I decided to keep it here for googlers. This was not obvious to me, may be not obvious to someone else. - mehov

1 Answers

0
votes

Turns out this was actually the right setup.

I didn't realise the lower Router::prefix call with no middleware would negate the above Router::scope call (i.e. act as an exception), but it did.