symfony测试 - 经过身份验证不适用于新请求

时间:2017-08-16 19:02:58

标签: symfony testing php-7 symfony-3.1

Good morning. 

Tldr:我认为,我需要Symfony Test Client与js xhr设置类似的东西:withcredentals:true。

Symfony 3.1. I have action in rest api controller:

    /**
     * @Rest\GET("/get-stuff")
     * @Rest\View
     * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
     */
    public function GetStuffAction($userId)
    {
        // get userId from session
        $userId = $this->getUser()->getId();
        $em = $this->getDoctrine()->getManager();
        $Stuff = $em->getRepository('MyApiBundle:Stuff')->findBy(['user' => $userId]);
        return $this->viewGroup($Stuff, ['stuff']);
    }    

它确实有效。

现在我想要测试,所以我有:

    class TestCase extends WebTestCase
    {
         public function testIndex()
         {
            $this->client = self::createClient();
            $this->storage = new MockFileSessionStorage(__dir__.'/../../../../app/cache/test/sessions');
            $this->session = new Session($this->storage);
            $this->logIn($this->getUser(), new Response());
            $this->client->request('GET', '/get-stuff');
            $content = $this->client->getResponse()->getContent();
            $this->assertEquals({"message":"Full authentication is required to access this resource.","code":0},$content);
    }

        public function logIn(User $user, Response $response) 
        {
             $this->session->start();
             $this->cookie = new Cookie('MOCKSESSID', $this->storage->getId());
             $this->cookieJar = new CookieJar();
             $this->cookieJar->set($this->cookie);
             $this->token = new UsernamePasswordToken($user, 'user', 'main', $user->getRoles());
             $this->session->set('_security_main', serialize($this->token));


             $this->getSecurityManager()->loginUser(
                 $this->container->getParameter('fos_user.firewall_name'),
                 $user,
                 $response
             );

             $this->session->save();
         }
    }

测试它给了我一条消息:“访问此资源需要完全身份验证”。在方法logIn()之后,我可以读取与已登录用户连接的会话数据。 如何在此部分中记录以便不接收有关身份验证的消息?:

$this->client->request('GET', '/get-stuff');
        $content = $this->client->getResponse()->getContent();

更多细节: 1.我的测试类扩展了WebTestCase。 2.我的用户被FosUserBundle覆盖。

我想这就像在javascript中: var xhr = new XMLHttpRequest(); xhr.withCredentials = true; 但我不知道是什么。

提前感谢您帮助解决我的问题!

1 个答案:

答案 0 :(得分:0)

好的,我是很好的方法:

public function logIn(User $ user){         $ session = $ this-> session;

    $firewallContext = 'secured_area';

    $token = new UsernamePasswordToken($user, 'user', 'main', $user->getRoles());
    $session->set('_security_'.$firewallContext, serialize($token));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $this->client->getCookieJar()->set($cookie);
}