Search code examples
cakephpmiddlewarecsrf-protectioncakephp-3.x

Is CakePHP 3 CsrfProtectionMiddleware automatic?


I'm in the process of rewriting an application to use most of CakePHP 3.5's features in general. However, one thing is stumping me. I have the CsrfProtectionMiddleware set up as described, and can see the token in the forms generated.

The cookbook, however, does not describe a method of "checking" the request data sent. It seemingly only states how to set things up:

$csrf = new CsrfProtectionMiddleware();
$middlewareQueue
    // Catch any exceptions in the lower layers,
    // and make an error page/response
    ->add(ErrorHandlerMiddleware::class)

    // Handle plugin/theme assets like CakePHP normally does.
    ->add(AssetMiddleware::class)

    // Add routing middleware.
    ->add(new RoutingMiddleware($this))
    ->add($cookies)
    ->add($csrf);

When a request is received, is the check performed by CakePHP 3.5 automatically when csrf is enabled?


Solution

  • Yes, the check is performed automatically. Quote from the API docs:

    This middleware adds a CSRF token to a cookie. The cookie value is compared to request data, or the X-CSRF-Token header on each PATCH, POST, PUT, or DELETE request.

    If the request data is missing or does not match the cookie data, an InvalidCsrfTokenException will be raised.

    https://api.cakephp.org/3.5/class-Cake.Http.Middleware.CsrfProtectionMiddleware.html