Search code examples
phpphpunittddsymfony

Symfony login with PHPUnit throws invalid CSRF token


I am trying to write PHPUnit test for a login form - that should work.. because in browser manually, I can login with the user. I keep getting the error "Invalid CSRF token", over and over again. What am I doing wrong? It is a very basic login form, not much logic at all:

This is the phpunit test for login:

public function testLoginSuccess()
{
  $client = $this->createClient();
  $csrfToken = $client->getContainer()->get('security.csrf.token_manager')->refreshToken('authenticate');

  $client->request(
      'POST',
      '/login_check',
      array(
          "app_user_login" => array(
              "_csrf_token"               => $csrfToken,
              "_username"                 => 'tester',
              "_password"                 => 'test1234'
          )
      ),
      array(),
      array('HTTP_X-Requested-With' => 'XMLHttpRequest')
  );

  $response = $client->getResponse();

  $this->assertEquals(
      Response::HTTP_OK,
      $response->getStatusCode()
  );
}

In the view, I am rendering the token as:

            <input type="hidden" name="_csrf_token"
                   value="{{ csrf_token('authenticate') }}">

And my security yml is the following:

firewalls:
    main:
        pattern: ^/
        form_login:
            provider: user_provider
            csrf_token_generator: security.csrf.token_manager
            csrf_parameter: _csrf_token
            csrf_token_id: authenticate
            default_target_path: /
            success_handler: app.security.authentication_handler
            failure_handler: app.security.authentication_handler
            login_path:  /login
            check_path:  /login_check
            require_previous_session: false
        logout:       true
        anonymous:    true

When running the test, it always jumps into the onAuthenticationFailure Handler and gives me the error message "Invalid csrf" .. I tried all I could think off -- this is a very strange behaviour. How to use csrf properly within a phpunit test?


Solution

  • I found the solution .. I've got one array too much within another when passing parameters ....