【问题标题】:How to create CSRF token for Cakephp 3 PHPunit testing?如何为 Cakephp 3 PHPunit 测试创建 CSRF 令牌?
【发布时间】:2015-09-16 02:48:26
【问题描述】:

在我的 CakePHP 3 应用程序中启用 CSRF 令牌和 SSL 后,我正试图让我的单元测试再次工作。

如何为如下测试创建或生成令牌?还是我只是出于测试目的禁用它?

public function testLogin() {
    $this->get('/login');
    $this->assertResponseOk();

    $data = [
        'email' => 'info@example.com',
        'password' => 'secret'
    ];
    $this->post('/login', $data);

    $this->assertResponseSuccess();
    $this->assertRedirect(['controller' => 'Users', 'action' => 'dashboard']);
}

【问题讨论】:

    标签: unit-testing cakephp csrf cakephp-3.0


    【解决方案1】:

    官方文档has good approach since version 3.1.2.

    您只需在发帖前致电$this->enableCsrfToken(); 和/或$this->enableSecurityToken(); 即可使用令牌成功执行请求。

    如官方示例所示:

    public function testAdd()
    {
        $this->enableCsrfToken();
        $this->enableSecurityToken();
        $this->post('/posts/add', ['title' => 'Exciting news!']);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 2015-08-28
      • 2012-03-20
      • 2019-07-20
      相关资源
      最近更新 更多