How to disable Csrf Protection for API in CakePHP 5?

35 Views Asked by At

If you added API prefix routing and want to disable Csrf Protection for POST, PUT API requests then follow the below listed steps.

First add API prefix routing into config/routes.php

$routes->prefix('api', function (RouteBuilder $routes): void {
          $routes->setExtensions(['json', 'xml'])
          $routes->connect(
            '/token',
            ['controller' => 'Users', 'action' => 'token']
            )->setMethods(['POST']);
          $routes->resources('Users');
          $routes->resources('Pages');
      });

Now update src/Application.php.

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
    {

        $csrf = new CsrfProtectionMiddleware(['httponly' => true]);

        // Disable CSRF for API
        // Token check will be skipped when callback returns `true`.
        $csrf->skipCheckCallback(function ($request) {
            // Skip token check for API URLs.
            if ($request->getParam('prefix') === 'Api') {
                return true;
            }
        });
        .
        .
        .
        .
        ->add($csrf);
        return $middlewareQueue;
    }

I tried above code and it is working.

0

There are 0 best solutions below