'Symfony 5 - HttpClient, Add "Authorization bearer 123456789azertyuiop" in headers data
I would like to attach authentication information in the header of an HTTP request using HttpClientInterface.
(I already have 45 other methods that work very well) but my problem occurs when I try to send a file with the multipart/form-data content-type.
I take the code from the original documentation below to stay on a very simple case but I can't join my data in the generated ones.
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
$formFields = [
'regular_field' => 'some value',
'file_field' => DataPart::fromPath('/path/to/uploaded/file')
];
$formData = new FormDataPart($formFields);
$client->request('POST', 'https://...', [
'headers' => $formData->getPreparedHeaders()->toArray(),
'body' => $formData->bodyToIterable(),
]);
Here's what I'm trying to do
$myHeader = [
'Authorization' => 'Bearer ' . $this->getUser()->getToken()
];
$params = [
'headers' => array_merge($myHeader, $formData->getPreparedHeaders()->toArray()),
'body' => $formData->bodyToIterable(),
];
And here's how it's translated so the API doesn't understand what I send it and return me back a 400 bad request
"headers" => [
"Authorization" => "Bearer eecd39xxxxxxxxede8e66433d3aea693"
0 => "Content-Type: multipart/form-data; boundary=ujDYAsPF"
]
It's a relatively common case in principle so I guess there is a solution? thank you.
Solution 1:[1]
It seems you're looking for auth_bearer. This one is mentioned in the documentation.
So the request would look something like the following...
$httpClient->request("GET", "/the/request/path", [
'auth_bearer' => $this->getUser()->getToken()
]);
Solution 2:[2]
When you use getPreparedHeaders you have to add your own headers to the Header object it returns and then use toArray() to pass it to your request.
$formData = new FormDataPart($data);
$header = $formData->getPreparedHeaders();
$header->addTextHeader('Authorization', "Bearer $token");
It will give you the proper key/value header
"headers" => [
"Authorization" => "Bearer eecd39xxxxxxxxede8e66433d3aea693"
"Content-Type" => "multipart/form-data; boundary=ujDYAsPF"
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HoppyB |
| Solution 2 | yowaiOtoko |
