How diable csrfToken in form

Hello everyone

when I create a form with a method get it adds the csrf token

how can I disable this for forms that have the get method

<?= $this->Form->create(null,  ['url' => ['controller' => 'Forums', 'action' => 'index'], 'method' => 'GET']) ?>
        <div class="input-group">
          <input type="text" class="form-control" name="query" placeholder="Rechercher un sujet" value="<?= $query ?? '' ?>">
          <div class="input-group-btn">
            <button class="btn btn-default input-search-forum" type="submit">
              <i class="fa fa-search"></i><span class="search-span">Rechercher</span>
            </button>
          </div>
        </div>
        <?= $this->Form->end() ?>

Change from ‘method’ => ‘get’ to ‘type’ => ‘get’

2 Likes

My guess would be that you want to have a form which is not checked by the CSRF protection feature.

Even though I don’t understand why you would need to have such a thing (because its a safety feature) you can of course achieve what you want via setting a bit more config.

You need to whitelist your action you are calling in the CSRF Middleware. See:
https://book.cakephp.org/4/en/security/csrf.html#skipping-csrf-checks-for-specific-actions

So in your case adjust your middleware method inside your src/Application.php

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
    $csrf = new CsrfProtectionMiddleware();

    // Token check will be skipped when callback returns `true`.
    $csrf->skipCheckCallback(function ($request) {
        $controller = $request->getParam('controller');
        $action = $request->getParam('action');
        $plugin = $request->getParam('plugin');
        // Skip token check for API URLs.
        if ($controller === 'Forums' && $action === 'index') {
            return true;
        }
    });
    
    $middlewareQueue
        // Here are your already present ->add() calls which should basically stay the same
        // BUT you have to replace the already present CsrfProtectionMiddleware instance with your new one from above
        ->add($csrf);

    return $middlewareQueue;
}

This stopped /items/edit?_csrfToken=kJxgXjE...snippage...wQ%3D%3D&item_id=75 being appended and now I get what I wanted /items/edit?item_id=70

Thanks @MarekDM

1 Like