Guzzle Bearer Authorization header cannot be setted to request - symfony

I am trying to set an Authorization header with Guzzle/6.2.0 on Ubuntu 18.04.1. But I cannot set it. Can anyone help me with this problem?
I have following code:
use GuzzleHttp\Client;
$url = 'my_url';
$client = new Client();
$response = $client->get( $url, [
'headers' => [
'Authorization' => "Bearer {$my_token}"
]
]);
echo '<pre>';
print_r(json_decode($response->getBody(), true));
echo '</pre>';
The server returns all the headers from the request. Here in this function, the authorization header is no longer present.
return $this->handleView($this->view([
'headers' => $request->headers->all()
], 200));
And answer is:
Array {
[headers] => Array {
[host] => Array{ [0]=>'my_url' }
[user-agent] => Array { [0] => GuzzleHttp/6.2.0 curl/7.58.0 PHP/7.1.22-1+ubuntu18.04.1+deb.sury.org+1 }
[x-php-ob-level] => Array{ [0] => 1 }
}
}
So, "Authorization" was not setted.
Thank you!

Can you try with the debug option turned on? What do you see in the logs?
Also can you upgrade to the latest version? I don't remember any bugs related to the question, but if you want to report it in the end, you have to do it against the latest version.

Related

How can I pass my UploadedFile data via http guzzle request?

I have two different website : my application and my backoffice (in Laravel)
I create an API route to store a document on my application. I made a request with Guzzle on my backoffice to store a document.
My guzzle http request on backoffice website :
public static function storeDocument($token, $request)
{
$client = new \GuzzleHttp\Client([
'Content-Type' => 'multipart/form-data'
]);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
];
$datas = [
'document' => $request->file('document'),
'doc_name' => $request->doc_name ?? '',
];
$request = $client->post(env('API_URL') . '/api/document/store/', ['headers' => $headers, 'form_params' => $datas]);
$result = json_decode($request->getBody()->getContents());
return $result;
}
And there is my API route method on application website :
public function store(Request $request) {
$validator = Validator::make($request->all(), [
'document' => 'bail|required|mimes:pdf,doc,docs,csv,txt|max:2048',
'doc_name' => 'bail|string|max:80|nullable',
]);
if($validator->fails()){
return response()->json($validator->errors());
};
$document = $request->document;
$fileName = '';
if(isset($request->doc_name)) {
$fileName = $request->doc_name . '.' . $document->extension();
} else {
$fileName = $document->getClientOriginalName();
}
$result = Storage::putFileAs(
'documentations',
$document,
$fileName,
'public'
);
if($result) {
return response()->json(['success' => 'Le fichier a bien été enregistré'], 201);
} else {
return response()->json(['error' => $errors], 400);
};
}
It seems that my datas aren't sent correctly because storeDocument() gives me an error : 'This field is required'. So it looks like it can't find $request->document which is required...
And with Insomnia I have no error, my file is correctly save.
I want to specify that I pass correct datas to storeDocument.
That is the result of $request->file('document') :
Illuminate\Http\UploadedFile {#1354 ▼
-test: false
-originalName: "test.pdf"
-mimeType: "application/pdf"
-error: 0
#hashName: null
path: "/tmp"
filename: "phpPOxtfN"
basename: "phpPOxtfN"
pathname: "/tmp/phpPOxtfN"
extension: ""
realPath: "/tmp/phpPOxtfN"
aTime: 2022-08-25 14:30:14
mTime: 2022-08-25 14:30:13
cTime: 2022-08-25 14:30:13
inode: 4856076
size: 48632
perms: 0100600
owner: 33
group: 33
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
I'm stuck since several hours on this, does anyone has any idea to help me?
Thanks ;)
EDIT: I finally found that I have to pass 'multipart' instead of 'form_params' on my http request.
Moreover I found that I have to use fopen or file_get_contents to send raw datas...
So my storeDocument function looks like this now :
public static function storeDocument($token, $request)
{
$client = new \GuzzleHttp\Client([
'Content-Type' => 'multipart/form-data'
]);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
];
$datas = [
[
'name' => 'document',
'contents' => file_get_contents($request->file('document')),
],
[
'name' => 'doc_name',
'contents' => $request->doc_name ?? '',
]
];
$request = $client->post(env('API_URL') . '/api/document/store/', ['headers' => $headers, 'multipart' => $datas]);
$result = json_decode($request->getBody()->getContents());
return $result;
}
But it still doesn't work...
Continue searching...

HTTP/2 400 returned for URL when using symfoy HTTP Client to make post request

I want to transform a http post request tested with post man to symfony action :
I want to transform the payload to a json array in symfony to send data to url :
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\Routing\Annotation\Route;
class PushNotificationController extends AbstractController
{
/**
* #Route("/api/push_notification", name="push_notification")
*/
public function index()
{
$httpClient = HttpClient::create();
$response = $httpClient->request('POST', 'https://fcm.googleapis.com/fcm/send', [
'headers' => [
// 'Accept' => 'application/json',
// "Content-Type" => "application/json; charset=UTF-8",
'Authorization' => 'Bearer token'
],
'json' => [
'notification' => [
'title' => 'Portugal vs. Denmark',
'message' => 'My Notification Message',
'body' => '5 to 1',
],
'token' => 'token'
],
]);
$statusCode = $response->getStatusCode();
// $statusCode = 200
$contentType = $response->getHeaders()['content-type'][0];
// $contentType = 'application/json'
$content = $response->getContent();
// $content = '{"id":521583, "name":"symfony-docs", ...}'
$content = $response->toArray();
// $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
return $content;
}
}
I got this error :
I think it's an error about the payload . any suggestions please ?
Error 400 Invalid Json input:
Only applies for JSON requests. Indicates that the request could not
be parsed as JSON, or it contained invalid fields (for instance,
passing a string where a number was expected). The exact failure
reason is described in the response and the problem should be
addressed before the request can be retried.
so i guess you need to review your json that you sent.
also , you can use some of the FCM Bundle from Knp or git.

HttpClient Component Authentication

I need to to be authentificate when create a HTTP request, in the documentation
$httpClient = HttpClient::create([
'auth_basic' => ['user#gmail.com', '45#8888'],
]);
$httpClient = HttpClient::create([
// HTTP Basic authentication with only the username and not a password
'auth_basic' => ['the-username'],
// HTTP Basic authentication with a username and a password
'auth_basic' => ['the-username', 'the-password'],
// HTTP Bearer authentication (also called token authentication)
'auth_bearer' => 'the-bearer-token',
]);
So when write
$response = $httpClient->request('GET', 'https://...', [
// use a different HTTP Basic authentication only for this request
'auth_basic' => ['the-username', 'the-password'],
// ...
]);
An exception is throwed
Symfony\Component\HttpClient\Exception\ClientException: HTTP/1.1 400
Bad Request returned for "http://site.test/login_check".
Is the exeption throwed because i haven't post the field user[_token] ?
If yes how to generate it and add to the request ?
If anyone has already logged in with this component please give me the code :)
I used that and it works
Try, for Authentication and Request:
$httpClient = HttpClient::create();
$uri = 'http://test:xxxx/login_check';
$response = $httpClient->request('POST', $uri, [
'headers' => [
'Content-Type' => 'application/json',
],
'json' => [
'username' => 'jhon.doe#gmail.com',
'password' => 'jhon.doe'
],
]);
$statusCode = $response->getStatusCode();
if($statusCode == 200) {
$content = $response->getContent();
dd($content);
}
// JWT Request Http
$uri = 'http://test.xxx/api/xxxx';
$response = $httpClient->request('GET', $uri, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer '.TOKEN
]
]);
$statusCode = $response->getStatusCode();
$content = $response->getContent();
dd($content);
//the easiest
$httpClient->request('POST', $url, [
'auth_bearer' => $jwt,
'body' => $data,
])->getContent();

How to store and log for all http request and response in wordpress?

I want to store all outgoing http request from my wordpress site. I want to store all internal and external http request and response also request made with curl. Any help should be useful to me.
Hook into WP_Http::_dispatch_request()
function fn_log_http_request_response( $wp_http_response, $request, $url ) {
$request = [
'method' => $request['method'],
'url' => $url,
'headers' => $request['headers'],
'body' => $request['body'],
];
if($wp_http_response instanceof WP_Error) {
$response = [
'errors' => $wp_http_response->errors,
'error_data' => $wp_http_response->error_data,
];
} else {
$response = [
'status' => [
'code' => wp_remote_retrieve_response_code($wp_http_response),
'message' => wp_remote_retrieve_response_message($wp_http_response),
],
'headers' => wp_remote_retrieve_headers($wp_http_response)->getAll(),
'body' => wp_remote_retrieve_body($wp_http_response),
];
}
error_log(print_r([
'request' => $request,
'response' => $response,
], true));
return $wp_http_response;
}
// hook into WP_Http::_dispatch_request()
add_filter('http_response', 'fn_log_http_request_response', 10, 3 );
Adopted from hinnerk-a
You can also try the following plugin as well
https://wordpress.org/plugins/log-http-requests

How to integrate PowerBI in symfony4

I want to integrate an Advanced statistics in my project symfony 4
so i decide to use PowerBI ( if you have an alternative please let me know),
my question is how to integrate it in my local project symfony4 and in relation with my database MySQL
Untill now , there no Symfony bundle for power bi , but instead you can use :
the adevait/power-bi
In case you don't find options you are looking for , you can using the native power bi rest api
You need to create an account and manage it by creating your dataset etc ...
Requirement :
GuzzleHttp
The point here is to create for example a service that manage calling the api :
example for authentication :
try {
/** #var GuzzleHttp\Client $client **/
$response = $client->post(
'https://login.windows.net/<tenant-id>/oauth2/token',
[
"headers" => [
"Accept" => "application/json"
],
'form_params' => [
'resource' => 'https://analysis.windows.net/powerbi/api',
'client_id' => $this->clientId,
'client_secret' => $this->secret,
'grant_type' => 'password',
'username' => $this->username,
'password' => $this->password,
'scope' => 'openid',
]
]
);
$body = json_decode($response->getBody()->getContents(), true);
return $body['access_token'];
} catch (ClientException $e) {
return ['error' => $e->getMessage()];
}
At this point , you need the token to call other endpoint , so you need to inject the returned token in the header of any request you send like :
try {
/** #var GuzzleHttp\Client $client **/
$client->post(
https://api.powerbi.com/v1.0/myorg/groups/<group-id>/datasets/<dataset-id>/tables/<table-name>/rows,
[
'headers' => [
"Accept" => "application/json",
"Authorization" => sprintf("Bearer %s", $token),
],
'json' => $data
]
);
return true;
} catch (ClientException $e) {
return false;
}
Hope that help you .

Resources