2013-08-05 85 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. 
     // ... 
    } 
}