How to Simulate HTTP Authentication in a Functional Test

Version: 2.4
Edit this page

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

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

How to Simulate HTTP Authentication in a Functional Test

If your application needs HTTP authentication, pass the username and password as server variables to createClient():

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

You can also override it on a per request basis:

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

When your application is using a form_login, you can simplify your tests by allowing your test configuration to make use of HTTP authentication. This way you can use the above to authenticate in tests, but still have your users log in via the normal form_login. The trick is to include the http_basic key in your firewall, along with the form_login key:

  • YAML
  • XML
  • PHP
1
2
3
4
5
# app/config/config_test.yml
security:
    firewalls:
        your_firewall_name:
            http_basic: ~
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.