HttpClient Component Authentication - symfony

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();

Related

how to retrieve post response variable outside in reactphp

My code is as follows:
require __DIR__.'/vendor/autoload.php';
use Psr\Http\Message\ResponseInterface;
$loop = React\EventLoop\Factory::create();
$client = new React\Http\Browser($loop);
$data = [
'name' => [
'first' => 'Alice',
'name' => 'Smith',
],
'email' => 'alice#example.com',
'userid' => 'alice',
];
$client->post(
'https://httpbin.org/post',
[
'Content-Type' => 'application/json',
],
json_encode($data)
)->then(function (ResponseInterface $response) {
$response = (string) $response->getBody();
return $response;
});
**echo $response;**
$loop->run();
I am able to get the response inside then function(). but I cannot retrieve the response value outside.
I like to send multiple asynchronous POST requests and collect each responses and echo all of them at once.
How can I access the response variable from outside of post()->then()?
I could get the response when I need a response with deferred and promise method.
First, I assigned the request and response method to $promise.
And I was able to simply get the response with $deferred->resolve();
require __DIR__.'/vendor/autoload.php';
use Psr\Http\Message\ResponseInterface;
$loop = React\EventLoop\Factory::create();
$client = new React\Http\Browser($loop);
$deferred = new React\Promise\Deferred();
$promise = $deferred->promise();
$data = [
'name' => [
'first' => 'Alice',
'name' => 'Smith',
],
'email' => 'alice#example.com',
'userid' => 'alice',
];
$promise = $client->post(
'https://httpbin.org/post',
[
'Content-Type' => 'application/json',
],
json_encode($data)
)->then(function (ResponseInterface $response) {
$response = (string) $response->getBody();
return $response;
});
echo $deferred->resolve();
$loop->run();

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.

Integrating wordpress and laravel login

I am developing three area for my website.. using WordPress (Front Page), XenForo (Forum), and Laravel (Member Area) ... i already succeed integrating my laravel and XenForo, so when XenForo user login to Member Area my function will check if the user already exist (If XenForo user exist then laravel will create the user in database using XenForo user data, if not exist then login failed)
Now i want to do the same for WordPress .. when user login to member area the function will check if WordPress user is exist or not .. if exist then new user will be created using wordpress user data (name, email, password, and token if possible) if not exist then login failed, but how do i do this? unlike XenForo .. i can't find WordPress API documentation for getting user data
Edit 1 :
This is my login function
public function login_post(Request $request){
// XENFORO API AUTH START
$http = Http::withHeaders([
'XF-Api-Key' => 'SECRET'
])->asForm()->post('http://forum.mywebsite.com/api/auth', [
'login' => $request->email,
'password' => $request->password
]);
if(isset($http['errors'])){
return redirect('login')->with('error', 'Username and Password Error');
}
$name = $http['user']['username'];
$email = $http['user']['email'];
$password = $request->password;
$is_admin = $http['user']['is_admin'];
$user_id = $http['user']['user_id'];
// XENFORO API AUTH END
// WordPress API AUTH START
$client = new \GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'http://mywebsite.com/',
'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json", 'Authorization' => 'Basic ' . base64_encode( 'ADMIN' . ':' . 'PASSWORD' ),],
]);
$response = $client->get('users/', [
'query' => [
'email' => $request->email,
]
]);
return json_decode($response->getBody());
// WordPress API AUTH END
if (Auth::attempt(['email' => $email, 'password' => $password])) {
# code...
if(Auth::user()->role == 0){
return redirect('dashboard');
}
return redirect('login');
} else {
$newUser = new User;
$newUser->name = $name ;
$newUser->email = $email;
$newUser->password = bcrypt($password);
$newUser->role = $is_admin;
$newUser->save();
auth()->login($newUser, true);
return redirect('dashboard');
}
}
Edit 2 :
$client = new \GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'http://mywebsite.com/wp-json/wp/v2/',
'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json", 'Authorization' => 'Basic ' . base64_encode( 'ADMIN' . ':' . 'PASSWORD' ),],
]);
$response = $client->get('users/', [
'query' => [
'email' => $request->email,
]
]);
$response = json_decode($response->getBody());
$name = $response['username'];
$email = $response['email'];
$password = $request->password;
$is_admin = $response['role'];
$user_id = $response['id'];
The Response :
array:3 [▼
0 => {#287 ▼
+"id": 1
+"name": "Admin"
+"url": "http://www.mywebsite.com"
+"description": ""
+"link": "http://mywebsite.com/author/admin/"
+"slug": "admin"
+"avatar_urls": {#285 ▶}
+"meta": []
+"_links": {#281 ▶}
}
1 => {#274 ▼
+"id": 2
+"name": "Prima"
+"url": ""
+"description": ""
+"link": "http://mywebsite.com/author/prima/"
+"slug": "prima"
+"avatar_urls": {#272 ▶}
+"meta": []
+"_links": {#279 ▶}
}
2 => {#288 ▼
+"id": 3
+"name": "TEST ER"
+"url": ""
+"description": ""
+"link": "http://mywebsite.com/author/testing/"
+"slug": "testing"
+"avatar_urls": {#289 ▶}
+"meta": []
+"_links": {#291 ▶}
}
]
WordPress doesn't provide API to check user exists or not, however you can check this by using List Users API.
Here is what I have done in Laravel:
$client = new \GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'http://www.example.com',
'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json"],
]);
$response = $client->get('users/', [
'query' => [
'search' => 'example#email.com',
]
]);
return json_decode($response->getBody());
With Authorization:
Install this https://github.com/WP-API/Basic-Auth plugin and update headers, $username & $password refers to WP admin credentials.
$client = new \GuzzleHttp\Client([
// Base URI is used with relative requests
'base_uri' => 'http://www.example.com',
'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json", 'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),],
]);

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

sending JWT authorization guzzle

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();

Resources