【问题标题】:How to skip controller actions in case of authorization is not succeed in ZF2ZF2中授权不成功时如何跳过控制器动作
【发布时间】:2013-01-30 11:57:39
【问题描述】:

我正在 ZF2 上实现 REST API。现在我需要检查 Module.php 上的授权令牌,如果授权失败则返回错误。但我不知道如何从 Module.php 返回响应。

我在 onBootstrap 的 DISPATCH 事件中编写了代码来检查授权。现在,如果授权失败,如何在不访问控制器的情况下从 Module.php 返回错误。因为只有exit 函数/调用可以在不访问控制器的情况下返回。但在那种情况下,我没有得到任何回应。使用 json_encode(array) 看起来不像标准,因为我已经启用 ViewJsonStrategy 并在控制器中使用 JsonModel。

【问题讨论】:

标签: rest controller authorization zend-framework2


【解决方案1】:

您可以通过让侦听器返回响应来缩短事件,例如...

public function onBootstrap(EventInterface $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    // attach dispatch listener 
    $eventManager->attach('dispatch', function($e) {
        // do your auth checks...
        if (!$allowed) {
            // get response from event
            $response = $e->getResponse();
            // set status 403 (forbidden) 
            $response->setStatusCode(403);
            // shortcircuit by returning response
            return $response;
        }
    });
}

【讨论】:

  • 这个方法可行,但问题仍然存在。我需要发送错误消息,但我只能使用$response->setContent($data)。现在它作为 text/html 传递。即使使用 application/json 标头也不起作用。因此,发送所需信息的唯一方法是使用 json_encode 数据,如$response->setContent(json_encode($data))。现在我已经启用了 ViewJsonStrategy 但我仍然需要添加 json_encode。
  • 经过更多分析后我发现,请求仍然进入控制器,因此在那里执行代码。看起来只有响应数据包是从 Module.php 设置的。否则所有的场景还是一样的:(
  • 在关闭后尝试添加第三个参数值 100。如果我理解正确,它将导致调度事件在控制器操作之前发生。在这里查看“事件”代码可能也值得一看:mwop.net/blog/2012-07-30-the-new-init.html
  • 经过大量时间检查,是的,它正在工作,(但是现在将是访问控制器对象 $e->getTarget() 的场景)。
猜你喜欢
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
  • 2013-05-29
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多