2013-08-05 34 views
0

我正在使用Zend Framework 1.12编写REST API。我想检查控制器插件中的“授权”标题。Zend Framework 1.12插件用于检查“授权”标头

我把代码的插件

$authorizationHeader = $request->getHeader('Authorization'); 
if(empty($authorizationHeader)) { 
    $this->getResponse()->setHttpResponseCode(400); 
    $this->getResponse()->setBody('Hello'); 
    die(); //It doesn't work 
} 

的preDispatch行动的问题是,之后它仍然被称为控制器的动作。我试过'die()','exit'。我的问题是如何从插件返回响应并且不要调用控制器的操作。

回答

1

做过类似REST API与Zend几个星期前使用这种方法:

类瓦尔/ Consts:

protected $_hasError = false; 
const HEADER_APIKEY = 'Authorization'; 

我preDispatch:

public function preDispatch() 
{ 
    $this->_apiKey = ($this->getRequest()->getHeader(self::HEADER_APIKEY) ? $this->getRequest()->getHeader(self::HEADER_APIKEY) : null); 

    if (empty($this->_apiKey)) { 
     return $this->setError(sprintf('Authentication required!'), 401); 
    } 

    [...] 

} 

我定制SETERROR功能:

private function setError($msg, $code) { 
    $this->getResponse()->setHttpResponseCode($code); 
    $this->view->error = array('code' => $code, 'message' => $msg); 
    $this->_hasError = true; 

    return false; 
} 

然后,只需检查是否有错误已设置你的函数中:

public function yourAction() 
{ 
    if(!$this->_hasError) { 

    //do stuff 

    } 
} 

如果您使用ContextSwitch里和JSON,然后用你的错误阵列将自动返回&显示,如果有错误occours:

public function init() 
{ 
    $contextSwitch = $this->_helper->getHelper('contextSwitch'); 
    $this->_helper->contextSwitch()->initContext('json'); 

    [...] 

} 

希望这有助于

+0

感谢详细的答复。所以,如果在每个api动作中检查这个条件(!$ this - > _ hasError)吗?我宁愿直接从插件重定向。 – Tamara

+0

即使认证错误发生,我也使用此解决方案来输出其他数据/信息。如果你不想检查每个动作,只需将'setError'函数中的第3行更改为'抛出新的Zend_Exception($ code,$ msg)' – simplyray

+0

好的,谢谢。此外,我想我可以抛出一些自定义异常来区分REST API异常与其他错误控制器中的异常。 – Tamara

1

因为检查头通常是一个低级别的请求操作,你可以做头部验证,然后抛出一个异常,如果没有有效的插件dispatchLoopStartup。然后在你的错误控制器中,返回适当的响应。这将阻止该操作被分派/运行,并且可以被应用于任何控制器/操作而不用修改任何控制器代码。

控制器插件:

class AuthHeader extends Zend_Controller_Plugin_Abstract 
{ 
    public function dispatchLoopStartup(\Zend_Controller_Request_Abstract $request) 
    { 
     // Validate the header. 
     $authorizationHeader = $request->getHeader('Authorization'); 

     if ($invalid) { 
      throw new Zend_Exception($error_message, $error_code); 
     } 
    } 
} 

错误处理程序:

class ErrorController extends Zend_Controller_Action 
{ 
    public function init() 
    { 
     // Enable JSON output for API originating errors. 
     if ($this->isApiRequest($this->getRequest())) { 
      $contextSwitch = $this->_helper->getHelper('contextSwitch'); 
      $contextSwitch->addActionContext('error', 'json') 
          ->setAutoJsonSerialization(true) 
          ->initContext('json'); 
     } 
    } 

    public function errorAction() 
    { 
     // Handle authorization header errors 
     // ... 

     // Handle errors 
     // ... 
    } 

    public function isApiRequest($request) 
    { 
     // Determine if request is an API request. 
     // ... 
    } 
}