This should be done with event in ZF2 for more details: click here also this code may help you. http://pastebin.com/FFGVCpki
public function init() {
// Attach Event to EventManager
$events = StaticEventManager::getInstance ();
// Add event of authentication before dispatch
$events->attach ( 'Zend\Mvc\Controller\AbstractActionController', 'dispatch', array (
$this,
'authPreDispatch'
), 110 );
}
public function authPreDispatch($event){
$target = $event->getTarget ();
$serviceLocator = $target->getServiceLocator();
// Do what ever you want to check the user's identity
$url = $event->getRouter ()->assemble ( array (
"controller" => "<controller>"
), array (
'name' => '<route name>'
) );
$response = $event->getResponse ();
$response->setHeaders ( $response->getHeaders ()->addHeaderLine ( 'Location', $url ) ));
$response->setStatusCode ( 302 );
$response->sendHeaders ();
exit ();
}