您可以使用下面的代碼的每個控制器內部
public function onDispatch(\Zend\Mvc\MvcEvent $e)
{
if (! $this->authservice->hasIdentity()) {
return $this->redirect()->toRoute('login');
}
return parent::onDispatch($e);
}
您還可以在模塊的onBootstrap功能(),您需要使用ZF2事件相匹配的路線查詢會話:
$auth = $sm->get('AuthService');
$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' => 'login'
));
$response = $e->getResponse();
$response->getHeaders()
->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, - 100);
其中$列表將包含不需要處理的路線列表:
$list = array('login', 'login/authenticate');