Symfony Http Client default headers not added

Viewed 3017

I'm using the Http Client to send a request to an external API. According to the documentation I can add default headers to a specific route like so:

framework:
  http_client:
    scoped_clients:
      the_api:
        base_uri: '%env(the_url)%'
        headers:
          Authorization: 'Bearer %env(my_token)%'

That doesn't work for me. I also tried this option:

auth_bearer: '%env(my_token)%'

same effect.

In the service I use to make the request I have:

$response = $client->request('POST', $theUrl, [
    'body' => $dataArray
]);

With the above configuration I get a 403 response, as if the token is not sent. If I add it to the request() function however it works:

$response = $client->request('POST', $theUrl, [
    'body' => $dataArray,
    'headers' => [
        'Authorization' => 'Bearer ' . $myToken
    ]
]);

I'm looking for a way to avoid fetching the token in my service or controller. In the future I might send other requests to the API (or a different API) and I don't want to set the token for each one.

If it matters $theUrl is https. Symfony and Http Client versions: 4.4

2 Answers

You must use the client name the_api in your case.

#config/packages/framework.yaml
framework:
    http_client:
        scoped_clients:
            name_client:
                base_uri: 'http://ip:port/'
                auth_basic: 'user:password'

client name here name_client

#src/Controller/MyController.php
...
public function __construct(HttpClientInterface $name_client)
{
    $this->client = $name_client;
}
...

$name_client will contain an instance of the ScopingHttpClient class with the specified parameters

Enjoy!

I had a similar problem, my scoped client doesn't add default authorization header. My solution was to inject the token in my service and initialize a brand new flat HttpClient object like this:

$client = \Symfony\Component\HttpClient\HttpClient::create(['headers' => [
        'Authorization' => 'Bearer '. $this->token,
    ]]);
Related