Slim-Website icon indicating copy to clipboard operation
Slim-Website copied to clipboard

Documentation unclear with before and after middleware

Open scorgn opened this issue 2 years ago • 1 comments

The middleware concepts page for Slim documentation is not exactly clear on the difference between before and after middleware.

On lines 5-9 it says that you can have middleware complete before and after the Slim application, and that before middleware would be useful to protect from cross-site request forgery.

Then on lines 73-81 it shows an example of two different middleware callables, one being $beforeMiddleware and the after being $afterMiddleware.

I think that this gives off the impression that the $beforeMiddleware callable is the same type of middleware that is described as middleware that would execute before the Slim application runs. The $beforeMiddleware callable is actually an "after middleware" though, because the first thing it does in the callable is handle the request.

I know that the behavior of the middleware is defined in PSR-15 but it may be good to clarify how to perform middleware logic before the application runs and how to perform middleware logic after the application runs. An example of a middleware that short-circuits the middleware flow and returns a response without calling $handler->handle() may be good to have as well.

scorgn avatar Oct 22 '21 17:10 scorgn

I think you are right. The $beforeMiddleware is actually an outgoing middleware because it handles things after the handle method. I agree, it is confusing and should be changed as follows:

$beforeMiddleware = function (Request $request, RequestHandler $handler) {
    $authorization = $request->getHeaderLine('Authorization');

    // Validate bearer token
    // If invalid, throw a HttpForbiddenException
    // ...

    return $handler->handle($request);
};

or this:

$beforeMiddleware = function (Request $request, RequestHandler $handler) {
    $csrfToken = $request->getHeaderLine('X-CSRF-Token');

    // Validate CSRF token
    // If invalid, throw a HttpForbiddenException
    // ...

    return $handler->handle($request);
};

odan avatar Oct 22 '21 19:10 odan