Skip to content

How to Simulate HTTP Authentication in a Functional Test

Warning: You are browsing the documentation for Symfony 4.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.2 (the current stable version).

Authenticating requests in functional tests can slow down the entire test suite. This could become an issue especially when the tests reproduce the same steps that users follow to authenticate, such as submitting a login form or using OAuth authentication services.

This article explains some of the most popular techniques to avoid these issues and create fast tests when using authentication.

Hashing Passwords Faster Only for Tests

By default, password encoders are resource intensive and take time. This is important to generate secure password hashes. In tests however, secure hashes are not important, so you can change the encoders configuration to generate password hashes as fast as possible:

1
2
3
4
5
6
7
8
# config/packages/test/security.yaml
encoders:
    # Use your user class name here
    App\Entity\User:
        algorithm: auto # This should be the same value as in config/packages/security.yaml
        cost: 4 # Lowest possible value for bcrypt
        time_cost: 3 # Lowest possible value for argon
        memory_cost: 10 # Lowest possible value for argon

Using a Faster Authentication Mechanism Only for Tests

When your application is using a form_login authentication, you can make your tests faster by allowing them to use HTTP authentication. This way your tests authenticate with the simple and fast HTTP Basic method whilst your real users still log in via the normal login form.

The trick is to use the http_basic authentication in your application firewall, but only in the configuration file used by tests:

1
2
3
4
5
6
# config/packages/test/security.yaml
security:
    firewalls:
        # replace 'main' by the name of your own firewall
        main:
            http_basic: ~

Tests can now authenticate via HTTP passing the username and password as server variables using the second argument of createClient():

1
2
3
4
$client = static::createClient([], [
    'PHP_AUTH_USER' => 'username',
    'PHP_AUTH_PW'   => 'pa$$word',
]);

The username and password can also be passed on a per request basis:

1
2
3
4
$client->request('DELETE', '/post/12', [], [], [
    'PHP_AUTH_USER' => 'username',
    'PHP_AUTH_PW'   => 'pa$$word',
]);

Creating the Authentication Token

If your application uses a more advanced authentication mechanism, you can't use the previous trick, but it's still possible to make tests faster. The trick now is to bypass the authentication process, create the authentication token yourself and store it in the session.

This technique requires some knowledge of the Security component internals, but the following example shows a complete example that you can adapt to your needs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// tests/Controller/DefaultControllerTest.php
namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class DefaultControllerTest extends WebTestCase
{
    private $client = null;

    public function setUp()
    {
        $this->client = static::createClient();
    }

    public function testSecuredHello()
    {
        $this->logIn();
        $crawler = $this->client->request('GET', '/admin');

        $this->assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
        $this->assertSame('Admin Dashboard', $crawler->filter('h1')->text());
    }

    private function logIn()
    {
        $session = self::$container->get('session');

        // somehow fetch the user (e.g. using the user repository)
        $user = ...;

        $firewallName = 'secure_area';
        // if you don't define multiple connected firewalls, the context defaults to the firewall name
        // See https://symfony.com/doc/current/reference/configuration/security.html#firewall-context
        $firewallContext = 'secured_area';

        // you may need to use a different token class depending on your application.
        // for example, when using Guard authentication you must instantiate PostAuthenticationGuardToken
        $token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles());
        $session->set('_security_'.$firewallContext, serialize($token));
        $session->save();

        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);
    }
}
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version