Authentication in functional tests in Symfony 2.1

后端 未结 5 731
梦谈多话
梦谈多话 2020-12-13 05:15

I am currently in the process of migrating a 2.0.* project to the current 2.1 beta of Symfony.

In my functional tests i currently have this code to create a client w

5条回答
  •  旧巷少年郎
    2020-12-13 05:35

    I can suggest another solution (thus it working for me). I have an custom authentication provider, with complicated logic and I can't use http_basic mechanic at all.

    You need to create special Action like this

     //TestAuthController.php
     public function authTestAction(Request $request)
     { 
       // you can add different security checks as you wish
       $user_id = $request->query->get("id");
       // find user  by $user_id using service or user provider service from firewall config
       $token = new UsernamePasswordToken($user, null, $firewallName, array($role));
        // or another authenticated token
       $this->container->get('security.context')->setToken($token);
     }
    

    add routing_test.yml and plug it just as routing_dev.yml

    Important thing that this authentication route must exists only in test enviroment, for security reasons.

     //app/config/routing_test.yml
     // ... the same routes as in routing_dev.yml
    _testauth:
        pattern:  /__test
        defaults: { _controller: MyBundle:TestAuth:authTest }
    

    Then in test just send client to this url

    public function testSomething()
    {
        $client = static::createClient();
        $client->request('GET','/__test',array('id'=>146));
        $this->assertTrue($client->getContainer()->get('security.context')->isGranted('ROLE_USER')) //it will pass;
    }
    

提交回复
热议问题