php - ACL授权失败后ZF3重定向

标签 php zend-framework2 zend-framework3 zf3

我有一个带有 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/

相关文章:

Php(eval vs call_user_func vs 变量函数...)

javascript - Ajax 调用不会触发 Zend 2 EVENT_DISPATCH 事件

mysql - 在 Zend 3 中设置数据库参数

zend-framework - 我不懂模块

php - Magento - 具有 1000 种颜色选项的可配置产品会减慢产品详细信息页面的加载时间

php - 从另一个表单提交表单,$_POST 值

php - 对 500 万行的数据库进行 boolean 搜索,非常慢

php - ZF2 中的 CORS POST 请求变为 OPTIONS 请求

doctrine-orm - 如何在带有 zf-apigility-doctrine 的 Apigility 应用程序中开始使用 Doctrine 2?

css - Zend 3 样式表不包含在 IE 中