LoginSignup
1
2

More than 3 years have passed since last update.

【CakePHP3.8】CakePHP3.8のCsrfProtectionMiddlewareを特定動作時に無効化する

Last updated at Posted at 2019-12-09

実際のコード

Application.php
Router::scope('/', function (RouteBuilder $routes) {
    // Register scoped middleware for in scopes.
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));
    /**
     * Apply a middleware to the current route scope.
     * Requires middleware to be registered via `Application::routes()` with `registerMiddleware()`
     */
    if (empty($_POST["postFlg"])){
        $routes->applyMiddleware('csrf');
    };

解説

Application.php
Router::scope('/', function (RouteBuilder $routes) {
    // Register scoped middleware for in scopes.
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));
    /**
     * Apply a middleware to the current route scope.
     * Requires middleware to be registered via `Application::routes()` with `registerMiddleware()`
     */
    $routes->applyMiddleware('csrf');

元々はこうなっています。

$routes->applyMiddleware('csrf');

この一行がCsrfProtectionMiddlewareを実際に聞かせるもの。
if文で、postFlgの値がPOSTされた時には働かないようにしています。

多分良い方法じゃない

csrfcomponentならいい感じに無効化出来るものもあったし、
csrfmiddleware自体を全部切る方法は簡単に見つかったのですが...
すぐに見つからなかったです。

最後に

PHP自体業務では2週間くらいしか使ってないですし、
CakePHPについては触る事自体2週間という所。
わかりやすく設計はされているんだろうなあ
となんとなくわかるのですが、今はまだ慣れていないですね。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2