通过AJAX请求处理Zend身份验证失败

时间:2010-08-02 00:39:08

标签: php zend-framework

我目前正在使用Zend Controller插件来检查身份验证。以下可能看起来很熟悉:

class SF_Plugin_Member_Auth extends Zend_Controller_Plugin_Abstract {

    public function preDispatch(Zend_Controller_Request_Abstract $request) {

        if (!SF_Auth::getInstance('Member')->hasIdentity()) {
            if ($request->getControllerName() !== 'auth' && $request->getControllerName() !== 'error') {
                $r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
                $r->gotoSimpleAndExit('login', 'auth', $request->getModuleName());
            }
        }
    }
}

我不确定的是处理未经过身份验证的AJAX请求的最佳方法。所以说有人试图使用通过AJAX发送的表单进行登录,Javascript应该如何知道它实际上需要将用户重定向到登录页面?

我的第一个想法是检查请求是否是一个AJAX请求,然后回显一个JSON对象,其中包含将用户重定向到的位置的详细信息 - 然后Javascript可以在返回的JSON对象中查找特定属性并将其用作“location.href”用户的URL。

以上有两个问题:

  1. 我不确定如何停止调度请求 - 我想要做的就是回显一个简单的JSON字符串,如果它是一个AJAX请求。
  2. 感觉不像Zend式的做事方式。
  3. 是否有人在那里遇到并解决了这种情况?

    非常感谢,

    詹姆斯。

1 个答案:

答案 0 :(得分:1)

您可以在响应对象中设置json值,并使用重定向器正常停止请求。

if (!SF_Auth::getInstance('Member')->hasIdentity()) {
    if ($request->getControllerName() !== 'auth' && $request->getControllerName() !== 'error') {
        if ($request->isXmlHttpRequest()) {
            $json = Zend_Json::encode(array('auth' => false, 'url' => 'http://foo.bar/login'));

            // Prepare response
            $this->getResponse()
                 ->setHttpResponseCode(200) // Or maybe HTTP Status 401 Unauthorized
                 ->setBody($json)
                 ->sendResponse();

            // redirectAndExit() cleans up, sends the headers and stopts the script
            Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit();
        } else {        
            $r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
            $r->gotoSimpleAndExit('login', 'auth', $request->getModuleName());
       }
    }
}

这将输出如下内容:

{"auth":false,"url":"http:\/\/foo.bar\/login"}