0

I am having a problem with adding some custom middleware to a slim 3 project that is using tuupola/cors and slim-jwt-auth with the jwt token stored in the header as bearer for authentication.

Everything is working well. When an ajax request is made from chrome, it first sends an options request to confirm that access is possible, and then sends the proper request with the jwt token in the header as Authorization: Bearer, but when I add an extra middleware to the flow, the options request is sent and returns 200 Ok, but the actual request is never sent.

This issue occures even when my custom middleware is taken down to the most minimal form, and makes not changest at all. The middleware is defined like this:

$container['App\Middleware\MyMiddleware'] = function ($c) {
    return new \App\Middleware\MyMiddleware(
        $c->get('logger')
    );
};

The middleware itself is as simple as:

namespace App\Middleware;

use Psr\Log\LoggerInterface;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;


class MyMiddleware {
    protected $logger;

    public function __construct(LoggerInterface $logger){
        $this->logger = $logger;
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) {

        $next($request, $response);

        return $response;
    }
}

Middleware is then added to all roots like this:

$app->add($container->get('App\Middleware\MyMiddleware'));
$app->add($container->get('Slim\Middleware\JwtAuthentication'));
$app->add($container->get('cors'));

with MyMiddleware disabed, both the options request and the followup request execute with the jwt token in the header, but with MyMiddleware enabled the options request is sent sucessfully, returning 200 OK, but the second request is never sent.

I am really stumped as to what is going on and how to debug it.

Finglish
  • 9,692
  • 14
  • 70
  • 114

1 Answers1

1

The PSR-7 Response object is immutable, so in you'r middleware you do execute the $next() (which should be the actual route or the next middleware) but you do not save that response from that.

class MyMiddleware {
    protected $logger;

    public function __construct(LoggerInterface $logger){
        $this->logger = $logger;
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) {

        $response = $next($request, $response);

        return $response;
    }
}
jmattheis
  • 10,494
  • 11
  • 46
  • 58