phpsymfonylexikjwtauthbundlesymfony-http-client

How to test a lexik_jwt_authentication protected API using http_client?


I am writing some functional test and looks like the client can't find the controller for the route, this is the code for my test:

$response = static::createClient()->request(
  'POST',
  '/api/login_check',
  [
    'body' => [
      'username' => 'username',
      'password' => 'secret123!#'
    ]
  ]
);

When I run the test I get this error:

2020-01-13T11:53:54+00:00 [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "Unable to find the controller for path "/api/login_check". The route is wrongly configured." at /var/www/html/vendor/symfony/http-kernel/HttpKernel.php line 130

also the route is configured as per route:debug

+--------------+---------------------------------------------------------+
| Property     | Value                                                   
|
+--------------+---------------------------------------------------------+
| Route Name   | api_login_check                                         
| Path         | /api/login_check                                        
| Path Regex   | #^/api/login_check$#sD                                  
| Host         | ANY                                                     
| Host Regex   |                                                         
| Scheme       | ANY                                                     
| Method       | POST                                                    
| Requirements | NO CUSTOM                                               
| Class        | Symfony\Component\Routing\Route                         
| Defaults     | NONE                                                    
| Options      | compiler_class: Symfony\Component\Routing\RouteCompiler |
+--------------+---------------------------------------------------------+

Which is exactly the same error I use to have using postman before to add the .htaccess file.


Solution

  • You are sending the wrong parameters with Http Client.

    You are not sending the authentication payload encoded as a JSON, nor you are sending the appropriate content-type headers. That's the reason the route is not being matched correctly.

    Instead of setting body, use the json key and Http Client will do the work for you.

    When uploading JSON payloads, use the json option instead of body. The given content will be JSON-encoded automatically and the request will add the Content-Type: application/json automatically too

    $response = static::createClient()->request(
            'POST',
            '/api/login_check',
            [
                'json' => [
                    'username' => 'username',
                    'password' => 'secret123!#'
                ]
            ]
        );