如何在AJAX中使用Zend Framework Form Hash(token)

时间:2010-03-19 03:18:39

标签: ajax zend-framework zend-form csrf

我已将Zend_Form_Element_Hash包含在表单multiplecheckbox表单中。我点击jQuery设置在单击复选框时触发AJAX请求,我使用此AJAX请求传递令牌。第一个AJAX请求工作得很好,但后续的请求失败了。

我怀疑可能一旦令牌已经过验证,它就会从会话中删除(hop = 1)。

使用AJAX来完成部分请求,使用Zend Framework Hash保护表单的攻击计划是什么?

6 个答案:

答案 0 :(得分:9)

我最终放弃使用Zend_Form_Element_Hash,只是手动创建了一个令牌,用Zend_Session注册它,然后在提交时检查它。

form.php的

$myNamespace = new Zend_Session_Namespace('authtoken');
$myNamespace->setExpirationSeconds(900);
$myNamespace->authtoken = $hash = md5(uniqid(rand(),1));
$auth = new Zend_Form_Element_Hidden('authtoken');
$auth->setValue($hash)
     ->setRequired('true')
     ->removeDecorator('HtmlTag')
     ->removeDecorator('Label');    

Controller.php这样

$mysession = new Zend_Session_Namespace('authtoken');
$hash = $mysession->authtoken;
if($hash == $data['authtoken']){
    print "success";
} else {
    print "you fail";
}

这似乎有效,并且仍然保持相对理智和安全。我仍然宁愿使用Hash元素,但我似乎无法使用AJAX。

谢谢大家。

答案 1 :(得分:8)

这是如何以ajax形式处理哈希字段:

class AuthController extends Zend_Controller_Action
{
    public function init()
    {
        $contextSwitch = $this->_helper->getHelper('contextSwitch');
        $contextSwitch->addActionContext('index', 'json')
                      ->initContext();
    }

    public function loginAction()
    {
        $form = new Application_Form_Login();
        $request = $this->getRequest();

        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                // some code ..
            } else {
                // some code ..

                // Regenerate the hash and assign to the view
                $reservationForm->hash->initCsrfToken();
                $this->view->hash = $reservationForm->hash->getValue();
            }
        }
        $this->view->form = $form;
    }
}

然后在你的视图脚本中..

<? $this->dojo()->enable()
                ->requireModule('dojox.json.query')
                ->onLoadCaptureStart() ?>
function() {
    var form = dojo.byId("login_form")
    dojo.connect(form, "onsubmit", function(event) {
        dojo.stopEvent(event);

        var xhrArgs = {
            form: this,
            handleAs: "json",
            load: function(data) {
                // assign the new hash to the field
                dojo.byId("hash").value = dojox.json.query("$.hash", data);

                // some code ..
            },
            error: function(error) {
                // some code ..
            }
        }
        var deferred = dojo.xhrPost(xhrArgs);
    });
}
<? $this->dojo()->onLoadCaptureEnd() ?>

希望现在还为时不晚:D

答案 2 :(得分:4)

有一个解决方案:

除了包含数据的表单外,还创建一个没有元素的表单。从控制器中,您实例化两个表单。同样在控制器中,您将元素哈希添加到空表单。两种形式都应该发送到愿景中。然后,在控制器中的条件“if($ request-&gt; isXmlHttpRequest())”中,您将呈现空表单。然后,使用方法“getValue()”获取哈希值。此值必须由Ajax响应发送,然后使用JavaScript替换已经过时的哈希值。为散列创建空表单的选项是避免其他元素(例如验证码)的问题,如果表单已呈现,则会再次生成其id,并且还需要替换新信息。验证将分开进行,因为有两种不同的形式。稍后您可以随时重用哈希(空)表单。以下是代码示例。

//In the controller, after instantiating the empty form you add the Hash element to it:
$hash = new Zend_Form_Element_Hash('no_csrf_foo');
$hash_form->addElement('hash', 'no_csrf_foo', array('salt' => 'unique'));

 //...

//Also in the controller, within the condition "if ($request->isXmlHttpRequest())" you render the form (this will renew the session for the next attempt to send the form) and get the new id value:
$hash_form->render($this->view);
$hash_value['hash'] = $hash_form->getElement('no_csrf_foo')->getValue();//The value must be added to the ajax response in JSON, for example. One can use the methods Zend_Json::decode($response) and Zend_Json::encode($array) for conversions between PHP array and JSON.

//---------------------------------------

//In JavaScript, the Ajax response function:
document.getElementById("no_csrf_foo").value = data.hash;//Retrieves the hash value from the Json response and set it to the hash input.

利奥

答案 3 :(得分:2)

表格哈希在原则上很棒,在实践中有点噩梦。我认为处理此问题的最佳方法是在发出请求时返回带有响应的新哈希,并根据需要更新表单标记或存储在内存中。

新的哈希可以从表单对象中获得,或者您可以从会话中读取它。

答案 4 :(得分:1)

你在问题​​中暗示了正确的答案:增加跳数。

在网上的ZF手册中有具体的提及,但他们更新了他们的手册,现在我找不到它(笑) - 否则我会为你发布链接。

答案 5 :(得分:0)

如果要在ajax端使用表单验证器,请使用以下代码:

Myform.php

class Application_Form_Myform extends Zend_Form
{ 
    # init function & ... 
    public function generateform($nohash = false)
    { 
        # Some elements
        if(!$nohash)
        {
           $temp_csrf = new Zend_Session_Namespace('temp_csrf'); 
           $my_hash = new Zend_Form_Element_Hash ( 'my_hash' );
           $this->addElement ( $my_hash , 'my_hash');  
           $temp_csrf->hash = $my_hash->getHash();
        }
        # Some other elements
    }
}

AjaxController.php

class AjaxController extends Zend_Controller_Action
{ 
    // init ... 
    public function validateAction()
    { 
         # ... 
         $temp_csrf = new Zend_Session_Namespace('temp_csrf');
         if($temp_csrf->hash == $params['received_hash_from_client'])
         {
             $Myform     = new Application_Form_Myform(); 
             $Myform->generateform(true);
             if($AF_Bill->isValid($params))
             {
                 # Form data is valid
             }else{
                 # Form invalid
             }
         }else{
             # Received hash from client is not valid
         }
         # ... 
    }
}