简体   繁体   中英

Pass custom variables in ZF2 routing config?

I'm thinking about the best way of implementing ACL. So - I need to protect certain routes. Some routes would be accessible only to users, some to guests and some to admins.

It seems like the best way of doing it would be by adding a $role variable in the routing config. So then I'd attach to post-route event, fetch the routeMatch and I would see if this user can enter this route.

How can I do that? Can I simply inject extra varibles like this:

'router' => array(
    'routes' => array(
        'route1' => array(
            'type' => 'Zend\Mvc\Router\Http\Regex',
            'options' => array(
                'regex' => '/some/route/1',
                'defaults' => array(
                    'controller' => 'Subscriber\Controller\View',
                    'action'     => 'route1',
                    'role'       => 'user', //extra
                ),
                'spec' => '/some/route/1',
            ),
        ),
        'route2' => array(
            'type' => 'Zend\Mvc\Router\Http\Regex',
            'options' => array(
                'regex' => '/some/route/2',
                'defaults' => array(
                    'controller' => 'Subscriber\Controller\View',
                    'action'     => 'route2',
                    'role'       => 'guest', //extra
                ),
                'spec' => '/some/route/2',
            ),
        ),
        //other routes....
    ),
),

Yes you can just add the router key like you have

'defaults' => array(
    'controller' => 'Subscriber\Controller\View',
    'action'     => 'route1',
    'role'       => 'user', //extra
),

And then you can checkit like this

public function onBootstrap(MvcEvent $e) {
    $application            = $e->getApplication();
    $eventManager = $application->getEventManager();
    $eventManager->attach(MvcEvent::EVENT_ROUTE, function(MvcEvent $e) {
        $e->getRouteMatch()->getParam('role');
    });
}

There are however modules made for this For example bjyoungblood/BjyAuthorize which works with ZfcUser

You should take a look at : ZfcRbac . It's well documented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM