我有一个带有 ACL 的新 ZF3 应用程序。现在我需要在未经授权的情况下重定向到错误页面(例如 403)。我认为最好的方法是触发一个事件,然后捕获它,但我失败了...
所有内容都在我的用户模块中,在 Module.php
(摘录)中:
namespace User;
use Zend\Mvc\MvcEvent;
use Zend\Permissions\Acl\Acl;
use Zend\Stdlib\Response ;
use Zend\View\Model\ViewModel;
[...]
class Module implements ConfigProviderInterface
{
[...]
public function onBootstrap(MvcEvent $e)
{
// Set event to check ACL, then to handle unauthorized access
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkProtectedRoutes'), 1);
$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'dispatchError'), -999);
// Init ACL
$this->initAcl($e);
}
public function initAcl(MvcEvent $e)
{
[...]
}
public function checkProtectedRoutes(MvcEvent $e)
{
// My access logic working fine. return if OK
[...]
// if authorization failed
$e->setError('ACL_ACCESS_DENIED') ;
$e->setParam('route', $route);
$e->getTarget()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $e);
}
public function dispatchError(MvcEvent $e)
{
// Check error type
$error = $e->getError();
switch ($error) {
case 'ACL_ACCESS_DENIED' :
// What should I do here ?
break;
default:
return ;
break;
}
return false ;
}
}
但是当我的事件被触发时,我的 dispatchError()
方法永远不会被调用,ZF3 哭了:
Catchable fatal error: Argument 1 passed to Zend\Mvc\View\Http\RouteNotFoundStrategy::detectNotFoundError() must be an instance of Zend\Mvc\MvcEvent, instance of Zend\EventManager\Event given, called in /xxxxxxx/vendor/zendframework/zend-eventmanager/src/EventManager.php on line 271 and defined in /xxxxxxxx/vendor/zendframework/zend-mvc/src/View/Http/RouteNotFoundStrategy.php on line 135
我哪里错了,我应该如何触发/捕捉这个事件?
最佳答案
由于您使用的是 ZF3,我可能建议将您的 ACL 逻辑从 Bootstrap 中移出并移至中间件中。如果 ACL 说请求没问题,你调用 $next 最终到达 Controller 。如果不是,则将响应的状态设置为 403 并返回响应。查看 zend-mvc 上的 docks,因为他们有一个针对这个问题的食谱示例。
https://docs.zendframework.com/zend-mvc/cookbook/middleware-in-listeners/
关于php - ACL授权失败后ZF3重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39397925/