CakePHP4で特定のコントローラーやアクションでCSRFを無効にする方法

CakePHP4で特定のコントローラーやアクションでCSRFを無効にする方法

108 回閲覧されました

みなさんこんにちは、jonioです。

CakePHP4ではCSRF対策がデフォルトで入っていますが解除したい場合がどうしても出てくると思います。

そんな時に特定のコントローラーやアクションでCSRFを解除できる方法を解説します。

Application.php

「CakePHPのプロジェクト > src > Application.php」を修正します、全部を記載するとコードが長くなるので必要な部分のみ掲載します。

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
  $middlewareQueue
  // Catch any exceptions in the lower layers,
  // and make an error page/response
  ->add(new ErrorHandlerMiddleware(Configure::read('Error')))

  // Handle plugin/theme assets like CakePHP normally does.
  ->add(new AssetMiddleware([
    'cacheTime' => Configure::read('Asset.cacheTime'),
  ]))

  // Add routing middleware.
  // If you have a large number of routes connected, turning on routes
  // caching in production could improve performance. For that when
  // creating the middleware instance specify the cache config name by
  // using it's second constructor argument:
  // `new RoutingMiddleware($this, '_cake_routes_')`
  ->add(new RoutingMiddleware($this))

  // Parse various types of encoded request bodies so that they are
  // available as array through $request->getData()
  // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
  ->add(new BodyParserMiddleware())

  ->add(new RoutingMiddleware($this))
    
  ->add(new AuthenticationMiddleware($this));


  //ここから削除
  // Cross Site Request Forgery (CSRF) Protection Middleware
  // https://book.cakephp.org/4/en/controllers/middleware.html#cross-site-request-forgery-csrf-middleware
  // ->add(new CsrfProtectionMiddleware([
  //     'httponly' => true,
  // ]));
  //ここまで削除


  //ここから追加
  $csrf = new CsrfProtectionMiddleware([
    'httponly' => true,
  ]);    
  
  $csrf->skipCheckCallback(function ($request) {
    if ($request->getParam('controller') == 'Posts' && $request->getParam('action') == 'uploadImage') {
      return true;
    }
  });
  
  $middlewareQueue->add($csrf);
  //ここまで追加
  

  return $middlewareQueue;
}

45行目〜49行目でCSRFを無効にするコントローラーとアクションを指定します。

45行目の「skipCheckCallback」メソッドを使えば実現できてメソッドの中でCSRFを除外するコントローラーとアクションを指定します。

今回の例だとコントローラー名はPostsでアクション名はuploadImageです。

短いですがこれで完成です。