当我尝试在Slim 4的以前的中间件中获取属性集时遇到问题。
我在app / middleware.php中使用中间件
我使用JwtAuthentication中间件检查令牌,并且要将解码的令牌传递给下一个中间件:CheckTokenInDatabaseMiddleware。
我用解码后的令牌返回了$ request:return $response->withAttribute("decoded", $arguments['decoded']);
在CheckTokenInDatabaseMiddleware中,$ request-> getAttribute('decoded')返回NULL
我有一个苗条的骨架,并使用它:
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;
}
}
答案 0 :(得分:0)
我找到了答案。
在苗条的中间件中,您必须记住它是FILO。
因此,如果要将属性从中间件A传递到中间件B,则必须以相反的顺序放置它们:
app / middleware.php
...
return function (App $app) {
$app->add(BMiddleware::class);
$app->add(AMiddleware::class);
};