I know the title might look strange, because API Authentications usually are about Oauth2, HttpAuth ... instead of Session. My case is not a popular practice, I need to implement the API inside a legacy project. At the moment, I can't have another choice by relying on this method.
I'm using Codeception2.4 to write API test for my application, which is built on Symfony2.8. As I understand, I can setup PhpBrowser client, which's similar to Acceptance test, or Symfony Module client, which's similar to Functional Test, for REST configuration to run API Test.
For PhpBrowser, I did the login by submit a form via the login page. It was success, everything worked as expected.
'username' => $username,
'password' => $password,
Then, I realised that I want to use Doctrine2 Module to build testing data without touching database. However, it could only work with Symfony Module client, otherwise the Repository was not the same between the data setup (haveInRepository()) and the client request, lead to the API Test process cannot recognise the created mocking data by Doctrine2 Module. Beside of that, I suppose Symfony Module client is faster than PhpBrowser client.
I switched to Symfony Module client and setup a another way for session login, which I defined in Tests\Helper\Api
public function setAuth($username)
/** @var Symfony $symfony */
$symfony = $this->getModule('Symfony');
/** @var Doctrine2 $doctrine */
$doctrine = $this->getModule('Doctrine2');
/** @var TokenStorageInterface $tokenStorage */
$tokenStorage = $symfony->grabService('security.token_storage');
/** @var Session $session */
$session = $symfony->grabService('session');
/** @var User $user */
$user = $doctrine->grabEntityFromRepository(User::class, ['username' => $username]);
$firewallName = 'secured_area';
$firewallContext = 'tuan';
$token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
$cookie = new Cookie($session->getName(), $session->getId());
Then I use it as below
Here, I got the problem. I couldn't login and the request always was redirected. I did some debug in the application login function and found that the Symfony TokenStorage doesn't contain my created mocking token for the request, even I've setup the client request is Symfony Module.
It is reached at my knowledge at this state, therefore, I'm looking for a help from our club. I hope the information is enough for understand.
Thanks for your reading.