Disabling CSRF on a specific action CakePHP 3

后端 未结 4 1342
孤独总比滥情好
孤独总比滥情好 2021-01-06 18:38

So, I have a table that is auto-generated using DataTables. An action in my CakePHP grabs the data for that table, and formats it into JSON for datatables to use, this is th

4条回答
  •  伪装坚强ぢ
    2021-01-06 19:12

    So i needed a fix for cakephp 3.7 and using $_SERVER['REQUEST_URI'] is realllly not the way to go here. So here is how you are supposed to do it after reading through some documentation.

    In src/Application.php add this function

    public function routes($routes)
    {
        $options = ['httpOnly' => true];
        $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware($options));
        parent::routes($routes);
    }
    

    Comment out the existing CsrfProtectionMiddleware

    public function middleware($middlewareQueue)
    { 
      ...
      //            $middlewareQueue->add(new CsrfProtectionMiddleware([
      //                'httpOnly' => true
      //            ]));
    }
    

    Open your config/routes.php add $routes->applyMiddleware('csrf'); where you do want it

    Router::prefix('api', function ($routes)
    {
      $routes->connect('/', ['controller' => 'Pages', 'action' => 'index']);
      $routes->fallbacks(DashedRoute::class);
    });
    
    Router::scope('/', function (RouteBuilder $routes)
    {
      $routes->applyMiddleware('csrf');
      $routes->connect('/', ['controller' => 'Pages', 'action' => 'dashboard']);
      $routes->fallbacks(DashedRoute::class);
    });
    

    Note that my api user now has no csrf protection while the basic calls do have it. If you have more prefixes don't forgot to add the function there aswell.

提交回复
热议问题