Middleware

Middleware objects give you the ability to ‘wrap’ your application in re-usable,composable layers of Request handling, or response building logic. Visually,your application ends up at the center, and middleware is wrapped aroud the applike an onion. Here we can see an application wrapped with Routes, Assets,Exception Handling and CORS header middleware.../_images/middleware-setup.pngWhen a request is handled by your application it enters from the outermostmiddleware. Each middleware can either delegate the request/response to the nextlayer, or return a response. Returning a response prevents lower layers fromever seeing the request. An example of that is the AssetMiddleware handlinga request for a plugin image during development.../_images/middleware-request.pngIf no middleware take action to handle the request, a controller will be locatedand have its action invoked, or an exception will be raised generating an errorpage.

Middleware are part of the new HTTP stack in CakePHP that leverages the PSR-7request and response interfaces. CakePHP also supports the PSR-15 standard forserver request handlers so you can use any PSR-15 compatible middleware availableon The Packagist.

Middleware in CakePHP

CakePHP provides several middleware to handle common tasks in web applications:

  • Cake\Error\Middleware\ErrorHandlerMiddleware traps exceptions from thewrapped middleware and renders an error page using theError & Exception Handling Exception handler.
  • Cake\Routing\AssetMiddleware checks whether the request is referring to atheme or plugin asset file, such as a CSS, JavaScript or image file stored ineither a plugin’s webroot folder or the corresponding one for a Theme.
  • Cake\Routing\Middleware\RoutingMiddleware uses the Router to parse theincoming URL and assign routing parameters to the request.
  • Cake\I18n\Middleware\LocaleSelectorMiddleware enables automatic languageswitching from the Accept-Language header sent by the browser.
  • Cake\Http\Middleware\HttpsEnforcerMiddleware requires HTTPS to be used.
  • Cake\Http\Middleware\SecurityHeadersMiddleware makes it easy to addsecurity related headers like X-Frame-Options to responses.
  • Cake\Http\Middleware\EncryptedCookieMiddleware gives you the ability tomanipulate encrypted cookies in case you need to manipulate cookie withobfuscated data.
  • Cake\Http\Middleware\CsrfProtectionMiddleware adds CSRF protection to yourapplication.
  • Cake\Http\Middleware\BodyParserMiddleware allows you to decode JSON, XMLand other encoded request bodies based on Content-Type header.
  • Cake\Http\Middleware\CspMiddleware makes it simpler to addContent-Security-Policy headers to your application.

Using Middleware

Middleware can be applied to your application globally, or to individualrouting scopes.

To apply middleware to all requests, use the middleware method of yourApp\Application class. Your application’s middleware hook method will becalled at the beginning of the request process, you can use theMiddlewareQueue object to attach middleware:

  1. namespace App;
  2.  
  3. use Cake\Http\BaseApplication;
  4. use Cake\Http\MiddlewareQueue;
  5. use Cake\Error\Middleware\ErrorHandlerMiddleware;
  6.  
  7. class Application extends BaseApplication
  8. {
  9. public function middleware(MiddlewareQueue $middlwareQueue): MiddlewareQueue
  10. {
  11. // Bind the error handler into the middleware queue.
  12. $middlwareQueue->add(new ErrorHandlerMiddleware());
  13. return $middlwareQueue;
  14. }
  15. }

In addition to adding to the end of the MiddlewareQueue you can doa variety of operations:

  1. $layer = new \App\Middleware\CustomMiddleware;
  2.  
  3. // Added middleware will be last in line.
  4. $middlwareQueue->add($layer);
  5.  
  6. // Prepended middleware will be first in line.
  7. $middlwareQueue->prepend($layer);
  8.  
  9. // Insert in a specific slot. If the slot is out of
  10. // bounds, it will be added to the end.
  11. $middlwareQueue->insertAt(2, $layer);
  12.  
  13. // Insert before another middleware.
  14. // If the named class cannot be found,
  15. // an exception will be raised.
  16. $middlwareQueue->insertBefore(
  17. 'Cake\Error\Middleware\ErrorHandlerMiddleware',
  18. $layer
  19. );
  20.  
  21. // Insert after another middleware.
  22. // If the named class cannot be found, the
  23. // middleware will added to the end.
  24. $middlwareQueue->insertAfter(
  25. 'Cake\Error\Middleware\ErrorHandlerMiddleware',
  26. $layer
  27. );

In addition to applying middleware to your entire application, you can applymiddleware to specific sets of routes usingScoped Middleware.

Adding Middleware from Plugins

Plugins can use their middleware hook method to apply any middleware theyhave to the application’s middleware queue:

  1. // in plugins/ContactManager/src/Plugin.php
  2. namespace ContactManager;
  3.  
  4. use Cake\Core\BasePlugin;
  5. use Cake\Http\MiddlewareQueue;
  6. use ContactManager\Middleware\ContactManagerContextMiddleware;
  7.  
  8. class Plugin extends BasePlugin
  9. {
  10. public function middleware(MiddlewareQueue $middlwareQueue): MiddlewareQueue
  11. {
  12. $middlwareQueue->add(new ContactManagerContextMiddleware());
  13.  
  14. return $middlwareQueue;
  15. }
  16. }

Creating Middleware

Middleware can either be implemented as anonymous functions (Closures), or classeswhich extend Psr\Http\Server\MiddlewareInterface. While Closures are suitablefor smaller tasks they make testing harder, and can create a complicatedApplication class. Middleware classes in CakePHP have a few conventions:

  • Middleware class files should be put in src/Middleware. For example:src/Middleware/CorsMiddleware.php
  • Middleware classes should be suffixed with Middleware. For example:LinkMiddleware.
  • Middleware must implement Psr\Http\Server\MiddlewareInterface.

Middleware can return a response either by calling $handler->handle() or bycreating their own response. We can see both options in our simple middleware:

  1. // In src/Middleware/TrackingCookieMiddleware.php
  2. namespace App\Middleware;
  3.  
  4. use Cake\Http\Cookie\Cookie;
  5. use Cake\I18n\Time;
  6. use Psr\Http\Message\ResponseInterface;
  7. use Psr\Http\Message\ServerRequestInterface;
  8. use Psr\Http\Server\RequestHandlerInterface;
  9. use Psr\Http\Server\MiddlewareInterface;
  10.  
  11. class TrackingCookieMiddleware implements MiddlewareInterface
  12. {
  13. public function process(
  14. ServerRequestInterface $request,
  15. RequestHandlerInterface $handler
  16. ): ResponseInterface
  17. {
  18. // Calling $handler->handle() delegates control to the *next* middleware
  19. // In your application's queue.
  20. $response = $handler->handle($request);
  21.  
  22. if (!$request->getCookie('landing_page')) {
  23. $expiry = new Time('+ 1 year');
  24. $response = $response->withCookie(new Cookie(
  25. 'landing_page',
  26. $request->getRequestTarget(),
  27. $expiry
  28. ));
  29. }
  30.  
  31. return $response;
  32. }
  33. }

Now that we’ve made a very simple middleware, let’s attach it to ourapplication:

  1. // In src/Application.php
  2. namespace App;
  3.  
  4. use App\Middleware\TrackingCookieMiddleware;
  5. use Cake\Http\MiddlewareQueue;
  6.  
  7. class Application
  8. {
  9. public function middleware(MiddlewareQueue $middlwareQueue): MiddlewareQueue
  10. {
  11. // Add your simple middleware onto the queue
  12. $middlwareQueue->add(new TrackingCookieMiddleware());
  13.  
  14. // Add some more middleware onto the queue
  15.  
  16. return $middlwareQueue;
  17. }
  18. }

Routing Middleware

Routing middleware is responsible for applying your application’s routes andresolving the plugin, controller, and action a request is going to. It can cachethe route collection used in your application to increase startup time. Toenable cached routes, provide the desired cache configuration as a parameter:

  1. // In Application.php
  2. public function middleware(MiddlewareQueue $middlwareQueue): MiddlewareQueue
  3. {
  4. // ...
  5. $middlwareQueue->add(new RoutingMiddleware($this, 'routing'));
  6. }

The above would use the routing cache engine to store the generated routecollection.

Security Header Middleware

The SecurityHeaderMiddleware layer makes it easy to apply security relatedheaders to your application. Once setup the middleware can apply the followingheaders to responses:

  • X-Content-Type-Options
  • X-Download-Options
  • X-Frame-Options
  • X-Permitted-Cross-Domain-Policies
  • Referrer-Policy

This middleware is configured using a fluent interface before it is applied toyour application’s middleware stack:

  1. use Cake\Http\Middleware\SecurityHeadersMiddleware;
  2.  
  3. $securityHeaders = new SecurityHeadersMiddleware();
  4. $securityHeaders
  5. ->setCrossDomainPolicy()
  6. ->setReferrerPolicy()
  7. ->setXFrameOptions()
  8. ->setXssProtection()
  9. ->noOpen()
  10. ->noSniff();
  11.  
  12. $middlewareQueue->add($securityHeaders);

Content Security Policy Header Middleware

The CspMiddleware makes it simpler to add Content-Security-Policy headers inyour application. Before using it you should install paragonie/csp-builder:

You can then configure the middleware using an array, or passing in a builtCSPBuilder object:

  1. use Cake\Http\Middleware\CspMiddleware;
  2.  
  3. $csp = new CspMiddleware([
  4. 'script-src' => [
  5. 'allow' => [
  6. 'https://www.google-analytics.com',
  7. ],
  8. 'self' => true,
  9. 'unsafe-inline' => false,
  10. 'unsafe-eval' => false,
  11. ],
  12. ]);
  13.  
  14. $middlewareQueue->add($csp);

If your application has cookies that contain data you want to obfuscate andprotect against user tampering, you can use CakePHP’s encrypted cookiemiddleware to transparently encrypt and decrypt cookie data via middleware.Cookie data is encrypted with via OpenSSL using AES:

  1. use Cake\Http\Middleware\EncryptedCookieMiddleware;
  2.  
  3. $cookies = new EncryptedCookieMiddleware(
  4. // Names of cookies to protect
  5. ['secrets', 'protected'],
  6. Configure::read('Security.cookieKey')
  7. );
  8.  
  9. $middlwareQueue->add($cookies);

Note

It is recommended that the encryption key you use for cookie data, is usedexclusively for cookie data.

The encryption algorithms and padding style used by the cookie middleware arebackwards compatible with CookieComponent from earlier versions of CakePHP.

Cross Site Request Forgery (CSRF) Middleware

CSRF protection can be applied to your entire application, or to specific routing scopes.

Note

You cannot use both of the following approaches together, you must chooseonly one. If you use both approaches together, a CSRF token mismatch errorwill occur on every PUT and POST request

By applying the CsrfProtectionMiddleware to your Application middlewarestack you protect all the actions in application:

  1. // in src/Application.php
  2. use Cake\Http\Middleware\CsrfProtectionMiddleware;
  3.  
  4. public function middleware($middlwareQueue) {
  5. $options = [
  6. // ...
  7. ];
  8. $csrf = new CsrfProtectionMiddleware($options);
  9.  
  10. $middlwareQueue->add($csrf);
  11. return $middlwareQueue;
  12. }

By applying the CsrfProtectionMiddleware to routing scopes, you can includeor exclude specific route groups:

  1. // in src/Application.php
  2. use Cake\Http\Middleware\CsrfProtectionMiddleware;
  3.  
  4. public function routes($routes) {
  5. $options = [
  6. // ...
  7. ];
  8. $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware($options));
  9. parent::routes($routes);
  10. }
  11.  
  12. // in config/routes.php
  13. Router::scope('/', function (RouteBuilder $routes) {
  14. $routes->applyMiddleware('csrf');
  15. });

Options can be passed into the middleware’s constructor.The available configuration options are:

  • cookieName The name of the cookie to send. Defaults to csrfToken.
  • expiry How long the CSRF token should last. Defaults to browser session.
  • secure Whether or not the cookie will be set with the Secure flag. That is,the cookie will only be set on a HTTPS connection and any attempt over normal HTTPwill fail. Defaults to false.
  • httpOnly Whether or not the cookie will be set with the HttpOnly flag. Defaults to false.
  • field The form field to check. Defaults to _csrfToken. Changing thiswill also require configuring FormHelper.

When enabled, you can access the current CSRF token on the request object:

  1. $token = $this->request->getAttribute('_csrfToken');

You can use the whitelisting callback feature for more fine grained control overURLs for which CSRF token check should be done:

  1. // in src/Application.php
  2. use Cake\Http\Middleware\CsrfProtectionMiddleware;
  3.  
  4. public function middleware($middlewareQueue) {
  5. $csrf = new CsrfProtectionMiddleware();
  6.  
  7. // Token check will be skipped when callback returns `true`.
  8. $csrf->whitelistCallback(function ($request) {
  9. // Skip token check for API URLs.
  10. if ($request->getParam('prefix') === 'Api') {
  11. return true;
  12. }
  13. });
  14.  
  15. // Ensure routing middleware is added to the queue before CSRF protection middleware.
  16. $middlewareQueue->add($csrf);
  17.  
  18. return $middlewareQueue;
  19. }

Note

You should apply the CSRF protection middleware only for URLs which handle statefulrequests using cookies/session. Stateless requests, for e.g. when developing an API,are not affected by CSRF so the middleware does not need to be applied for those URLs.

Integration with FormHelper

The CsrfProtectionMiddleware integrates seamlessly with FormHelper. Eachtime you create a form with FormHelper, it will insert a hidden field containingthe CSRF token.

Note

When using CSRF protection you should always start your forms with theFormHelper. If you do not, you will need to manually create hidden inputs ineach of your forms.

CSRF Protection and AJAX Requests

In addition to request data parameters, CSRF tokens can be submitted througha special X-CSRF-Token header. Using a header often makes it easier tointegrate a CSRF token with JavaScript heavy applications, or XML/JSON based APIendpoints.

The CSRF Token can be obtained via the Cookie csrfToken.

Body Parser Middleware

If your application accepts JSON, XML or other encoded request bodies, theBodyParserMiddleware will let you decode those requests into an array thatis available via $request->getParsedData() and $request->getData(). Bydefault only json bodies will be parsed, but XML parsing can be enabled withan option. You can also define your own parsers:

  1. use Cake\Http\Middleware\BodyParserMiddleware;
  2.  
  3. // only JSON will be parsed.
  4. $bodies = new BodyParserMiddleware();
  5.  
  6. // Enable XML parsing
  7. $bodies = new BodyParserMiddleware(['xml' => true]);
  8.  
  9. // Disable JSON parsing
  10. $bodies = new BodyParserMiddleware(['json' => false]);
  11.  
  12. // Add your own parser matching content-type header values
  13. // to the callable that can parse them.
  14. $bodies = new BodyParserMiddleware();
  15. $bodies->addParser(['text/csv'], function ($body, $request) {
  16. // Use a CSV parsing library.
  17. return Csv::parse($body);
  18. });

HTTPS Enforcer Middleware

If you want your application to only be available via HTTPS connections you canuse the HttpsEnforcerMiddleware:

  1. use Cake\Http\Middleware\HttpsEnforcerMiddleware;
  2.  
  3. // Always raise an exception and never redirect.
  4. $https = new HttpsMiddleware([
  5. 'redirect' => false,
  6. ]);
  7.  
  8. // Send a 302 status code when redirecting
  9. $https = new HttpsMiddleware([
  10. 'redirect' => true,
  11. 'statusCode' => 302,
  12. ]);
  13.  
  14. // Send additional headers in the redirect response.
  15. $https = new HttpsMiddleware([
  16. 'headers' => ['X-Https-Upgrade', => true],
  17. ]);
  18.  
  19. // Disable HTTPs enforcement when ``debug`` is on.
  20. $https = new HttpsMiddleware([
  21. 'disableOnDebug' => true,
  22. ]);

If a non-HTTPs request is received that doesn’t use GETa BadRequestException will be raised.