SLIM FRAMEWORK 3:无法将变量从中间件传递到控制器

时间:2018-08-18 07:40:07

标签: php middleware slim-3

我的代码有什么问题?我无法将变量从Auth中间件传递给控制器​​。在控制器中,属性为“ null”。

索引:

$c = new \Slim\Container($configuration);
$api = new \Slim\App($c);

$api->group('/', function () use ($api) {
$this->post('login', '\AuthController:login');
...
$this->post('getIngredientsCategories', '\IngredientsController:getIngredientsCategories');


})->add(new ApiAuthenticateController());

$api->run();

中间件(ApiAuthenticateController)

use \Firebase\JWT\JWT;

class ApiAuthenticateController
{
public function __invoke($request, $response, $next)
{
    $jwtDecoded = null;
    $req = $request->getUri()->getPath();
    $_req = RequestValidatorController::isRequestEnabled($req);

    if ($_req !== false) {
        if ($_req['login_required']) {
            $jwt = filter_var($request->getHeaderLine('AUTHORIZATION'), FILTER_SANITIZE_STRING);
            $jwt = explode(" ", $jwt)[1];
            try {
                $jwtDecoded = JWT::decode($jwt, JWT_SECRET, array('HS256'));
            } catch (\Exception $e) {
                return $this->deny_access($response);
            }
        }
        $request = $request->withAttribute('foo', $jwtDecoded);
        //HERE - attribute "foo" in $request exists - checked by var_dump()..
        $response = $next($request, $response);
        $response = $response->withHeader('Content-type', 'application/json');
        return $response;

    } else {
        return $this->deny_access($response);
    }
}

IngredientsController

class IngredientsController extends Controller
{
  private $_ingredients;

  public function __construct(\Interop\Container\ContainerInterface $container)
  {
      parent::__construct($container);
  }
}

控制器

class Controller
{
  private $request;
  private $response;
  protected $data;
  protected $method;
  protected $user;

  public function __construct(Interop\Container\ContainerInterface $container)
  {
     $this->request = $container->get('request');
     $this->response = $container->get('response');
     $this->data = (object)Tools::stripInput($this->request->getParsedBody());
     $this->method = $this->request->getUri()->getPath();
     $this->user = $this->request->getAttribute('foo');
     var_dump($this->user);
     // returns NULL. if $this->request->getAttributes()... returns empty
 }
}

请注意,本文中的代码已“清理”,为了便于阅读,删除了某些功能和条件。代码有效-很抱歉可能出现错字。

1 个答案:

答案 0 :(得分:3)

问题出在这里

在中间件ApiAuthenticateController中,您应该像这样更改代码

$request = $request->withAttribute('foo', $jwtDecoded);
// you should return the $next here not to do anything else
return $next($request, $response);

,并且在您的IngredientsController:getIngredientsCategories部分代码中,您应该返回

function getIngredientsCategories ($request, $response, $args){

    //do your job...
    $response = $response->withHeader('Content-type', 'application/json');
    return $response;

}

最后,在构造函数中,我认为中间件之后没有实际的$ request,因此您将在getIngredientsCategories函数中包含$ this-> request-> getAttributes()

希望有帮助。