使用CSRF令牌进行单元测试

时间:2016-06-06 09:01:09

标签: php phpunit csrf fuelphp

如何通过[curl request]设置csrf_token。(http://fuelphp.com/docs/classes/request/curl.html

通过

过滤我的令牌
class Controller_Core extends \Controller_Rest
{
    public function router($method, $params)
    {
        $token       = \Security::check_token();
        $method_type = \Request::main()->get_method();

        if ($token || $method_type === 'GET'){
            // call the REST router to process the request
            return parent::router($method, $params);
        }

        // validation failed, return a HTTP 401 and a message
        $rsp = ['error' => 'Not Authorized'];
        $this->response($rsp, 401);
    }
}

试过了

/**
 * @group Login
 */
class Test_Classes_Controller_Account_LoginTest extends \TestCase {

    /**
     * @covers Controller_Account_Login::post_index
     */
    public function testLoginToken () {
        $res = \Request::forge('/api/account/login/security_token.json')
                ->set_method('GET')
                ->execute()
                ->response();

        return \Security::fetch_token();
    }

    /**
     * @group Login
     * @depends testLoginToken
     */
    public function testLoginFailIncoCred ($token) {
        $_POST['csrf_token'] = $token;

        $curl = \Request::forge(\Uri::create('api/account/login.json'), 'curl')
                    ->set_method('POST')
                    ->set_params(array(
                        'email' => 'email',
                        'password' => 'password'
                    ))
                    ->execute()
                    ->response();

        var_dump($curl);
    }

}

我也尝试将csrf_token通过header-cookie,$ _POST params和curl params但仍然没有运气

如何发出从服务器动态设置/检索csrf_token的请求?

我可以为测试环境禁用csrf安全性,但我认为这不是测试的最佳实践。

任何建议/评论/回购将不胜感激

0 个答案:

没有答案