Closed
Description
Symfony version(s) affected: 5.3.7
Description
When calling multiple subsequent requests on the same instance of KernelBrowser, only the first request will have the proper authentication. Upon the 2nd request, the TokenStorage will be reinitialized and will have lost the token, meaning if the user needs to be authorized, the request will result in a 403 Access Denied response.
How to reproduce
I have a Controller function, which I'm trying to write a test for:
/**
* @Get ("/api/classroom/{classroomID}/challenges", name="get_challenges")
* @Security("is_granted('ROLE_MANAGER')")
* @param Request $request
* @param $classroomID
* @return JsonResponse
*/
public function GetChallenges(Request $request, $classroomID): JsonResponse
{
$em = $this->getDoctrine()->getManager();
/** @var BaseUser $user */
$user = $this->getUser();
...
}
With this test I'm trying to do 2 requests and compare them
class APITestCase extends WebTestCase
{
protected ObjectRepository $userRepo;
protected KernelBrowser $client;
protected function setUp(): void
{
parent::setUp();
$this->client = self::createClient();
$this->userRepo = static::getContainer()->get('doctrine')->getManager()->getRepository(BaseUser::class);
}
public function testGetChallenges_withInvisible()
{
$this->client->loginUser($this->userRepo->findOneBy(['username' => "test_user"]));
// This request will always return 200
$this->client->request('GET', '/api/classroom/1/challenges');
$content1 = $this->client->getResponse()->getContent();
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(), $content1);
// This request will always return 403 Access Denied
$this->client->request('GET', '/api/classroom/1/challenges?with-invisible=true');
$content2 = $this->client->getResponse()->getContent();
$this->assertEquals(200, $this->client->getResponse()->getStatusCode(), $content2);
$this->assertNotSameSize(json_decode($content1, true), json_decode($content2, true));
}
}
Possible Solution
I've tried:
- calling
loginUser
before everyrequest()
- retrying an identical request to see if there's a problem with second request
- reversing the order of the requests
None of these work.
I realize this might not be the best way to write a test, and we should be comparing to some static test fixture or something. I'll grant that point, but I've just been trying to migrate us over to using theloginUser()
function on KernelBrowser, because it's prefereable to our old method of using custom Authenticators which only work on test env. We have dozens of tests written in this format, and I still don't think that this should be the desire functionality.
Finally, I also realize that this might be an error in some other part of our configuration and any help working out what I've messed up would be a huge help.