【问题标题】:Using Dispatch Event to check authorization使用 Dispatch Event 检查授权
【发布时间】:2014-05-20 03:51:01
【问题描述】:

我正在尝试设置一个简单的 API。我有一个控制器,所有其他 API 控制器都在扩展,并且我已经像这样附加了一个调度侦听器。我创建了一个总是会失败的测试。将状态码设置为 401,并返回一条消息。但是,它仍然调用主控制器方法,并没有放弃来自 preDispatch 方法的请求。我可以在这里建立适当的响应并强制 ZF2 不继续执行请求的路线吗?我尝试只添加 exit() 语句,但客户端收到不完整的响应。

protected function attachDefaultListeners()
    {
        parent::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))
            {
                $this->getResponse()->setStatusCode(401);
                return new JsonModel(array('auth' => false, 'msg' => 'Try again'));
            }
        // Cookie not set, if we are authenticating, continue; otherwise return a failure
        } else {

        }

    }

【问题讨论】:

    标签: zend-framework2


    【解决方案1】:

    您需要返回一个响应对象来缩短流程,而不是 ViewModel:

    试试这样的:

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

    【讨论】:

      猜你喜欢
      • 2017-05-24
      • 1970-01-01
      • 2020-08-31
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多