Zend Framework 2 - Global check for authentication with ZFCUser

后端 未结 5 1386
误落风尘
误落风尘 2020-12-05 08:20

I installed ZFCUser successfully. Now I wonder if there is a way to globally check for authentication.

As outlined in the wiki there ar

5条回答
  •  情歌与酒
    2020-12-05 09:11

    To be honest, I don't think it is a good idea to block every page for a non-authenticated user. How would you access the login page?

    That said, you must know the page being accessed, to make a whitelist of pages accessible for anonymous visitors. To start, I'd suggest to include the login page. You can check pages the easiest by using their route. So check the current matched route against the whitelist. If blocked, act upon. Otherwise, do nothing.

    An example would be inside a Module.php from a module, for example your application:

    namespace Application;
    
    use Zend\Mvc\MvcEvent;
    use Zend\Mvc\Router\RouteMatch;
    
    class Module
    {
        protected $whitelist = array('zfcuser/login');
    
        public function onBootstrap($e)
        {
            $app = $e->getApplication();
            $em  = $app->getEventManager();
            $sm  = $app->getServiceManager();
    
            $list = $this->whitelist;
            $auth = $sm->get('zfcuser_auth_service');
    
            $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
                $match = $e->getRouteMatch();
    
                // No route match, this is a 404
                if (!$match instanceof RouteMatch) {
                    return;
                }
    
                // Route is whitelisted
                $name = $match->getMatchedRouteName();
                if (in_array($name, $list)) {
                    return;
                }
    
                // User is authenticated
                if ($auth->hasIdentity()) {
                    return;
                }
    
                // Redirect to the user login page, as an example
                $router   = $e->getRouter();
                $url      = $router->assemble(array(), array(
                    'name' => 'zfcuser/login'
                ));
    
                $response = $e->getResponse();
                $response->getHeaders()->addHeaderLine('Location', $url);
                $response->setStatusCode(302);
    
                return $response;
            }, -100);
        }
    }
    

提交回复
热议问题