【问题标题】:How to test Zend framework2 form which implements CSRF element?如何测试实现 CSRF 元素的 Zend framework2 表单?
【发布时间】:2023-04-06 17:40:01
【问题描述】:

我使用 Zend/Form 创建了登录表单,它包含输入元素以及 CSRF 元素。

<!-- sample login.phtml code snippet -->
<form method="post" action="/xyz">
<?php
 echo $this->formelement($form->get('email'));
 echo $this->formelement($form->get('password'));
 echo $this->formelement($form->get('csrf'));
 echo $this->formelement($form->get('submit'));
?>
</form>

由于针对 CSRF 元素的验证,以下测试用例失败。

public function testLogin()
{      
  //code goes here
  $params = array('email' => 'example@test.com', 'password' => 'example@test.com');
  $this->dispatch($url, $method, $params);
  //if the given username and password is correct the login page redirected to default home page
  $this->assertResponseStatusCode(302);
}

在上面的测试用例中,我设置了电子邮件和密码值,但我不知道如何设置 CSRF 元素。如何测试实现 CSRF 元素的表单?

【问题讨论】:

    标签: zend-framework zend-framework2 phpunit


    【解决方案1】:

    这可以通过以下方式轻松实现:

        $form = new LoginForm();
        $csrf = $form->get('csrf')->getValue();
        $params = array('email' => 'example@test.com', 
                        'password' => 'example@test.com', 
                        'csrf' => $csrf
        );
    

    除非您的表单需要表单管理器,否则您将不得不使用它,而不仅仅是实例化类,但这在单元测试中也很容易做到。

    更新:

    另一种有效的方法:

        $form = new LoginForm();
        $form->prepare();
    
        $params = new \Zend\Stdlib\Parameters(
                        array(
                                'csrf' => $_SESSION['Zend_Validator_Csrf_salt_csrf']['hash'],
                                'yourotherparams' => 'thingsandstuff'
                );
    
    
        $this->dispatch($url, $method, $params);
    

    【讨论】:

    • 如何在调度指定的 URL 时重用实例化的表单?
    • 当你执行此操作时,很确定 csrf 令牌只会被添加到 SessionContainer 中,并且当你发送到 url 时将在 SessionContainer 中可用
    • 测试用例仍然失败!我可以知道失败的原因吗?
    • $_SESSION['Zend_Validator_Csrf_salt_csrf']['hash']$form-&gt;get('csrf')-&gt;getValue(); 返回相同的哈希键。
    • 您的解决方案绝对完美! echo var_dump($loginForm-&gt;getMessages()); 当我使用你的逻辑设置 CSRF 时返回空数组。
    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    相关资源
    最近更新 更多