Middlewares

Middleware is logic that is run before and after each request and is modeled after Django's Middleware system. It offers the following hooks:

Middleware flow chart

To generate your own middleware, simply inherit from the Middleware class and overwrite the methods that should be used.

<?php

namespace OCA\MyApp\Middleware;

use \OCP\AppFramework\Middleware;


class CensorMiddleware extends Middleware {

    /**
     * this replaces "bad words" with "********" in the output
     */
    public function beforeOutput($controller, $methodName, $output): string {
        return str_replace('bad words', '********', $output);
    }

}

The middleware can be registered in the app's Application class:

Global Middlewares

Registered middleware will only intercept requests of the same app by default. To make a middleware global and trigger for other apps' middleware, add true as the second argument of the registerMiddleware call:

Dependency Injection Container Registration

Middleware can also be added using the registerMiddleware method of the container:

Parsing annotations

Sometimes it is useful to conditionally execute code before or after a controller method. This can be done by defining custom annotations. An example would be to add a custom authentication method or simply add an additional header to the response. To access the parsed annotations, inject the ControllerMethodReflector class:

<?php

namespace OCA\MyApp\Middleware;

use OCP\AppFramework\Middleware;
use OCP\AppFramework\Utility\IControllerMethodReflector;
use OCP\AppFramework\Http\Response;

class HeaderMiddleware extends Middleware {

  private $reflector;

  public function __construct(IControllerMethodReflector $reflector) {
      $this->reflector = $reflector;
  }

  /**
   * Add custom header if @MyHeader is used
   */
  public function afterController($controller, $methodName, Response $response): Response {
      if($this->reflector->hasAnnotation('MyHeader')) {
          $response->addHeader('My-Header', 3);
      }
      return $response;
  }
}