I'm trying to test this jwt authorization it works fine doing curl from console but when I try to use guzzle it gives me an empty response any help greatly appreciated
$client = new Client([
'base_uri' => 'http://localhost',
'timeout' => 2.0,
]);
$res = $client->request('GET', '/api/private', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer JWTTOKENHERE'
]
]);
I am also having trouble with this route /api/login_check it works fine with from php server but apache returns 404
curl -X POST http://localhos/api/login_check -d _username=johndoe -d _password=test
but with guzzle I get a 404 not found using LexikJWTAuthenticationBundle
$credentials = base64_encode('test#email.com:test');
$res = $this->client->request('POST','/api/login_check',
[
'headers' => [
'Authorization' => ['Basic ' . $credentials]
]
]);
dump($res);die();
Related
I want to post info to external api but I get error 422 all the time. Geting info and authorization works fine. I'm using Symfony Http Client, authorization and headers are defined in framework.yaml for now.
Api documentation fragment:
curl "https://business.untappd.com/api/v1/locations/3/custom_menus"
-X POST
-H "Authorization: Basic bmlja0BuZXh0Z2xhc3MuY286OW5kTWZESEJGcWJKeTJXdDlCeC0="
-H "Content-Type: application/json"
-d '{ "custom_menu": { "name": "Wine selection" } }'
My service fragment:
public function customMenu(): int
{
$response = $this->client->request(
'POST',
'https://business.untappd.com/api/v1/locations/'.$this->getLocationId().'/custom_menus',
[
'json' => [
['custom_menu' => ['name' => 'Wine selection']],
],
]
);
Try to encode json "manualy", before send. Just like that
//$jsonData = '{ "custom_menu": { "name": "Wine selection" } }';
$jsonData = json_encode(["custom_menu" => ["name" => "Wine selection"]]);
$response = $client->request(
'POST',
'https://business.untappd.com/api/v1/locations/'.$this->getLocationId().'/custom_menus',
[
'headers' => [
'Content-Type' => 'application/json',
],
'body' => $jsonData,
]
);
There are an error and some missing parameters you didn't include:
The most important : Authorization (if you didn't add it to your framework.yaml file under 'http_client' parameter).
Your link ends with 'custom_menus' not 'menus'.
The content-type.
You can test this correction:
public function customMenu(): int
{
$response = $this->client->request(
'POST',
'https://business.untappd.com/api/v1/locations/'.$this->getLocationId().'/custom_menus', //corrected '/custom_menus'
[
'auth_basic' => ['bmlja0BuZXh0Z2xhc3MuY286OW5kTWZESEJGcWJKeTJXdDlCeC0='], // To add
'headers' => [ // To add
'Content-Type' => 'application/json',
],
'json' => [
['custom_menu' => ['name' => 'Wine selection']],
],
]
);
// .....
}
I am developing a plugin for a wordpress website which interacts with a third party HTTP API.
For one specific request I am completely dependent on a response header. It's a Location header used for redirection, from which I need to get the url and query parameters.
The request:
return wp_remote_post($url, array(
'body' => http_build_query(array(
'token' => <omitted>,
'email' => <omitted>,
'password' => <omitted>
)),
'headers' => array(
'Content-Type' => 'application/x-www-form-urlencoded'
),
'redirection' => 0
));
While testing the request above I noticed the headers response fields are null and {}:
{
"headers": {},
"body": "",
"response": {
"code": 303,
"message": "See Other"
},
"cookies": [
{
"name": "JSESSIONID",
"value": "<omitted>",
"expires": null,
"path": "/<omitted>",
"domain": "test.<omitted>.com",
"host_only": true
}
],
"filename": null,
"http_response": {
"data": null,
"headers": null,
"status": null
}
}
The request is working fine in Postman, where all the expected response headers are clearly visible. I also turned off following redirections in Postman for this specific request to be able to intercept the Location header before the redirection occurs.
I have tried:
another wordpress instance: same issue, no headers
a local docker wordpress instance: same issue, no headers
a different http request (GET https://example.com): same issue, no headers
setting redirection to 1 instead of 0: same issue, no headers, BUT the redirect actually works, which means the Location header is present and wp_remote_post picked it up - this makes it even harder to understand why I cannot see or retrieve any headers.
Here's the response when I GET https://example.com:
{
"headers": {},
"body": "<omitted>",
"response": {
"code": 200,
"message": "OK"
},
"cookies":[],
"filename": null,
"http_response": {
"data": null,
"headers": null,
"status": null
}
}
I have been searching for hours and I haven't gotten a step closer to resolving this issue. Any assistance is most welcome.
edit: someone asked me for the cURL PHP code from Postman:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => '<omitted>/auth/login',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'token=<omitted>&email=<omitted>&password=<omitted>',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded',
'Cookie: JSESSIONID=<omitted>'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I worked around this issue by using another http library 'Requests'.
Wordpress usually includes this library by default.
$url = "$this->base_url/$this->base_path/auth/login";
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
$data = array(
'token' => <omitted>,
'email' => <omitted>,
'password' => <omitted>
);
$options = array(
'follow_redirects' => false
);
return Requests::post($url, $headers, $data, $options);
It does not solve the issue with wp_remote, but replaces it nicely for this specific 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.
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();
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.