若ACL不允许访问页面,则ZF2重定向


ZF2 redirect if ACL does not allow access to page

我有一个模块可以构建我的ACL树,它运行良好。

我在config/autoload目录中还有一个导航配置文件,它详细介绍了我的应用程序结构以及与条目相关的资源。我的应用程序模块配置中还有一个导航工厂。

所有这些都很好,我正在根据登录用户角色的权限和导航配置中页面的资源来呈现菜单。

我无法解决的是如何阻止访问用户无法访问的页面(隐藏在渲染导航菜单中的页面)。我希望在一个模块中进行管理。

我假设在我的Module.php文件中,在onBootstrap函数中,我需要对ACL运行isAllowed并重定向(如本问题中所述-从Module.php转发到另一个控制器/操作)。然而,isAllowed似乎需要查询资源。这需要从导航配置中获得。

如果我对isAllowed函数中所需的资源进行硬编码,我就可以实现这一点。实际上,我只需要从导航配置中获取当前页面请求的资源。

我确信这一定是标准功能,但我找不到任何具体的例子。

感谢您的帮助。

Chris

这就是您想要的,还是您想要如何从onBootstrap方法中访问您的配置?

public function onBootstrap($event) {
    $matched_route = $event->getRouteMatch()->getMatchedRouteName();
    $someOtherClass = new MyClassThatAuthenticatesRoutes();
    if(!($someOtherClass->isAllowed($matched_route)){
        $response = $event->getResponse();
        $response->setStatusCode(401);
        $response->setReasonPhrase('Not allowed!');
        return $response;
    }

如果你只是在寻找配置,你可以去:

 $sm = $e->getApplication()->getServiceManager();
 $config = $sm->get('config');

如果您需要匹配ACL的路由,请考虑执行以下操作:

/**
 * Retrieve the route match
 * 
 * @return string
 */
protected function getMatchRoute()
{
    $router  = $this->getServiceLocator()->get('router');
    $request = $this->getServiceLocator()->get('request');      
    $this->routeMatch = $router->match($request)->getMatchedRouteName();
    return $this->routeMatch;
}

然后在您的控制器中:

// note, $acl is just a class I wrote to extend class Zend'Permissions'Acl'Acl
// because I needed additional functionality    
$acl = new 'PATH_TO'Acl'Acl(); 
// checkAcl(), just however you plan on handling permissions
// $role is obviously just that, the role of the user, where ever 
// you are setting that.
// the second param is from the method in the above code block which is the 
// resource (page) you are wanting to check against
$access = $acl->checkAcl($role, $this->getMatchRoute());
// they don't have access so redirect them
if (!$access)
{
    return $this->redirect()->toRoute('your_route', array());
}

如果你需要看更多的代码,请告诉我,但希望这能让你开始。