ZF3 redirection after ACL authorization failed

2019-06-21 13:22发布

问题:

I have a new ZF3 application with ACL. Now I need, in case of unauthorized access, to redirect to an error page (403 for example). I think the best way is to fire an event, then catch it, but I failed...

All is in my User module, in Module.php (extracts):

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 ;
    }
}

But when my event is triggered, my dispatchError() method is never call, and ZF3 cry:

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

Where I am wrong and how should I trigger/catch this event ?

回答1:

Since you're using ZF3, I might suggest moving your ACL logic out of the bootstrap and into a middleware. If the ACL says the request is okay, you call $next which eventually gets to the controller. If it is not, you set the status on the response to 403 and return the response. Check out the docks on zend-mvc as they have a cookbook example for this very problem.

https://docs.zendframework.com/zend-mvc/cookbook/middleware-in-listeners/



回答2:

Even if it doesn't solve the event issue, this is how I solved the problem, returning the response directly in my checkProtectedRoutes() method:

// Erreur 403
$e->stopPropagation();

$baseModel = new ViewModel();
$baseModel->setTemplate('403');

$resolver = new TemplateMapResolver();
$resolver->setMap( ['403' =>  __DIR__ . '/../view/error/403.phtml']);

// Render view
$renderer = new PhpRenderer();
$renderer->setResolver($resolver);
$content = $renderer->render($baseModel);
$response = $e->getResponse();
$response->setStatusCode(403);
$response->getHeaders()->addHeaderLine('Location', $e->getRequest()->getBaseUrl() . '/login');
$response->setContent($content);
return $response ;


回答3:

I've got the same problem. Error trigger at your function checkProtectedRoutes(MvcEvent $e) should use triggerEvent method.

//ACL Permission test        
if ( ! $auth->hasPermission( $e ) ) {
    $e->setName(MvcEvent::EVENT_DISPATCH_ERROR);
    $e->setError('ACL_ACCESS_DENIED');            
    $target = $e->getTarget();
    $res = $target->getEventManager()->triggerEvent( $e );
    return $res->last();
}