【问题标题】:How to test Symfony2 api with DunglasAngularCsrfBundle如何使用 DunglasAngularCsrfBundle 测试 Symfony2 api
【发布时间】:2016-01-25 09:57:12
【问题描述】:

我将 Symfony2 与 DunglasAngularCsrfBundle 一起使用,当我运行我的 PHpunit 测试时,它得到错误 {"code":403,"message":"Bad CSRF token."}

如果 auth 用户使用 http basic

self::$user_client = static::createClient(array(), array(
    'PHP_AUTH_USER' => 'user1@mail.com',
    'PHP_AUTH_PW' => 'user1',
    'HTTP_HOST' => static::getHost()
));

此条件在 EventListener\AngularCsrfValidationListener 中返回 false

if (!$value || !$this->angularCsrfTokenManager->isTokenValid($value)) {
        throw new AccessDeniedHttpException('Bad CSRF token.');
    }

在测试中生成的令牌不相等,我尝试这样的另一个身份验证:

protected function logIn($email)
{
$this->client = static::createClient();

$user = $this->client->getContainer()
    ->get('doctrine')
    ->getManager()
    ->getRepository('UserBundle:User')
    ->findOneByEmail($email);

$providerKey = static::$kernel->getContainer()->getParameter('fos_user.firewall_name');
$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());


$session = $this->client->getContainer()->get('session');
$session->set('_security_'.$providerKey, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());

$this->client->getCookieJar()->set($cookie);

}

令牌未创建。在 Symfony\Component\Security\Csrf\CsrfTokenManager::isTokenValid: 中返回 false:

 $this->storage->hasToken($token->getId())

请帮忙解决这个问题,谢谢

【问题讨论】:

    标签: php symfony phpunit


    【解决方案1】:

    解决了

    self::$client->request('GET', '/') 
    

    在 cookie 中设置令牌

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2013-02-04
      • 2015-06-07
      • 2013-10-30
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多