1

I use FOSUserBundle for my User Authentication I have a controller, let's call it adminController which is reserved for User granted User::ADMIN_ROLE Everything works fine but I have an error when I try to write my functional Test

Inside my AdminControllerTest I have a method that try to test a page that need User::ADMIN_ROLE

My testAdminAccess() method

public function testAdminAccess()
{
    $session = $this->client->getContainer()->get('session');

    // the firewall context defaults to the firewall name
     = 'main';

    $user = $this->getUserByUsername('admin@yopmail.com');

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

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

    $this->client->followRedirects();

    $crawler = $this->client->request(
        'GET',
        'http://localhost/admin'
    );

    dump($crawler);
}

I'm always redirected to my login page

How can I keep the session to access some page that's protected by a specific Role?

What I'm already tried:

I'm using Symfony version 3.4

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
balzacLeGeek
  • 805
  • 5
  • 7

1 Answers1

0

The best is to login the user normally submitting the username and password like a standard user would do, I use a function like this (adapt your paths):

/**
 * Log the test user for the connected tests.
 */
public function login(string $username = null, string $password = null): KernelBrowser
{
    $client = static::createClient();

    // Login page
    $client->request('GET', '/en/login/');
    $this->assertTrue($kernelBrowser->getResponse()->isOk());

    // Auth
    $token = $client->getContainer()->get('security.csrf.token_manager')->getToken('authenticate');
    $client->request('POST', '/login_check', [
        '_csrf_token' => $token,
        '_username' => $username ?? 'test',
        '_password' => $password ?? 'test',
        '_remember_me' => 'on',
    ]);

    $this->assertTrue($client->getResponse()->isRedirect());
    $client->followRedirect();

    return $client;
}
COil
  • 7,201
  • 2
  • 50
  • 98