1

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

我把代码放在插件的 preDispatch 动作中

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

问题是在它之后控制器的动作仍然被调用。我试过'死()','退出'。我的问题是如何从插件返回响应并且不调用控制器的操作。

4

2 回答 2

2

几周前用这种方法用 Zend 做了一个类似的 REST API:

类变量/常量:

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

我的预调度:

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,那么如果发生错误,您的数组将自动返回并显示:

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

    [...]

}

希望这可以帮助

于 2013-08-06T07:25:15.577 回答
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.
        // ...
    }
}
于 2013-08-06T19:30:48.797 回答