Patrice Flao
Patrice Flao

Reputation: 501

How to getAttribute from middleware in slim

I have a problem when I try to get an attribute set in a previous middleware in Slim 4.

I use middlewares in app/middleware.php
I use JwtAuthentication middleware to check a token and I want to pass the decoded token to the next middleware : CheckTokenInDatabaseMiddleware.

I returned the $request with the decoded token : return $response->withAttribute("decoded", $arguments['decoded']);

In CheckTokenInDatabaseMiddleware the $request->getAttribute('decoded') returns NULL

I have a slim-skeleton and use this :

app/middleware.php

declare(strict_types=1);

use App\Application\Middleware\CheckTokenInDatabaseMiddleware;
use App\Application\Middleware\SessionMiddleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use Tuupola\Middleware\JwtAuthentication;

return function (App $app) {
    $app->add(SessionMiddleware::class);
    $app->add(new JwtAuthentication([
        "ignore" => ['/auth/signin', '/auth/signout'],
        'path' => ['/auth/me'],
        'secret' => getenv('JWT_SECRET'),
        "before" => function (Request $request, $arguments) {
            return $request->withAttribute("decoded", $arguments["decoded"]);
        }
    ]));
    $app->add(CheckTokenInDatabaseMiddleware::class);
};

app/Application/Middleware/CheckTokenInDatabaseMiddleware.php

declare(strict_types=1);

namespace App\Application\Middleware;

use App\Domain\User\UserRepository;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface as Middleware;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;

class CheckTokenInDatabaseMiddleware implements Middleware
{
    protected $userRepository;

    /**
     * {@inheritdoc}
     */
    public function process(Request $request, RequestHandler $handler): Response
    {
        $token = $request->getAttribute('decoded');

        var_dump($token); // returns NULL
        die();

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

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }
}

Upvotes: 2

Views: 1452

Answers (1)

Patrice Flao
Patrice Flao

Reputation: 501

I found the answer.
In slim middleware you have to remember it is FILO. So if you want to pass an attribute from middleware A to middleware B you have to put them in reverse order that is :

app/middleware.php

...
return function (App $app) {
    $app->add(BMiddleware::class);
    $app->add(AMiddleware::class);
};

Upvotes: 1

Related Questions