Using Dispatch Event to check authorization

I am trying to setup a simple API. I have a Controller all other API controllers are extending, and I have attached a dispatch listener like so. I created a test that will always fail. Set the status code to 401, and return a message. However, it's still calling the main Controller method and not abandoning the request from the preDispatch method. Can I build a proper response here and force ZF2 not to continue executing the requested route? I tried just adding an exit() statement, but the client side receives an incomplete response.

protected function attachDefaultListeners()
        $events = $this->getEventManager();
        $this->events->attach('dispatch', array($this, 'preDispatch'), 100);
        $this->events->attach('dispatch', array($this, 'postDispatch'), -100);

    public function preDispatch (MvcEvent $e)
        $this->dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
        // TODO: Check user and token from DB
        if (Cookie::isCookieSet())
            $cookie = Cookie::readCookie();
            if (empty($cookie->user))
                return new JsonModel(array('auth' => false, 'msg' => 'Try again'));
        // Cookie not set, if we are authenticating, continue; otherwise return a failure
        } else {




You need to return a response object to short circuit the process, not a ViewModel:

Try something like this:

$response = $this->getResponse();
$response->setContent(array('auth' => false, 'msg' => 'Try again'));
return $response; 

Need Your Help

Native Android Crash - Invalid Bitmap

android c++ bitmap native stack-trace

I am getting crash reports in the Google Developer Console with the abort message: "Error, cannot access an invalid/free'd bitmap here!". The below stack-trace is all I've been able to get a hold ...