Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3630

How to disable Csrf Protection for API in CakePHP 5?

$
0
0

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.


Viewing all articles
Browse latest Browse all 3630

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>