I'm trying to call a Laravel API using a Laravel Client.
Here is the code:
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://galaxy.dev/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => '3',
'client_secret' => 'rrhaEv0B6NAFLyMFqvZrY87gkquFF2UwhAHPtd8L',
'redirect_uri' => 'http://galaxy-game.dev/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});
I get this response from the API:
Client error: POST http://galaxy.dev/oauth/token resulted in a 400
Bad Request response: {"error":"invalid_request","message":"The
request is missing a required parameter, includes an invalid parameter
value, (truncated...)
I have noticed in the API error log this:
Client->request('post', 'http://galaxy.dev/oauth/token',
array('form_params' => array('grant_type' => 'authorization_code',
'client_id' => '3', 'client_secret' =>
'rrhaEv0B6NAFLyMFqvZrY87gkquFF2UwhAHPtd8L', 'redirect_uri' =>
'http://galaxy-game.dev/callback', 'code' => null), 'synchronous' =>
true)) in Client.php line 87
It says that
$request->code = null
Does anyone have any ideas why this might be? This seems to be the reason why it is failing. I have followed the Laravel docs exactly. Any help would be greatly appreciated!
Hi I fixed this by leaving the code value empty like this:
'code' => '',
Since $request->code is null, that probably causes that problem.
Related
I searched online but couldn't find a proper solution. I am calling a Spring service with a POST request using Guzzle Client, The service in case of any errors provides the error message in its URL param like: http://localhost:8085/fedauth/null?errMessage=Mot%20de%20passe%20invalide%20pour%20l'utilisateur%20Karan%20Sharma.. How can I fetch this param errMessage using Guzzle. Below is my code with Slim in PHP.
$data = [
'userName' => base64_encode($userName),
'userPassword' => base64_encode($userPassword),
'institution' => $institution,
'redirectUrl' => $redirectUrl,
'callerUrl' => $callerUrl,
'clientId' => $clientId,
'encryptMode' => $encryptMode,
'moodleLandPage' => $moodleLandPage,
'login' => $login,
'isEncrypted' => true
];
try {
$apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
} catch (Exception $exception) {
return $response->write(json_encode(['error' => $exception->getMessage(), "auth" => "0" ]));
}
I have tried using the getEffectiveUrl() method but its no longer supported in Guzzle 7
I guess you get the response as a redirect url? Your question is not clear in that point. In this case you can access it like this:
$apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
echo $apiResponse->getEffectiveUrl();
like here: https://docs.guzzlephp.org/en/5.3/http-messages.html#responses
Actually found the answer. You need to add track redirects option as true and then use $response->getHeaderLine('X-Guzzle-Redirect-History'); like below
$client = new GuzzleHttp\Client(['headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded'], 'verify' => false, 'allow_redirects' => ['track_redirects' => true]]);
$apiResponse = $client->post( $_ENV['FEDAUTH_API_URL'], ['form_params'=> $data]);
echo $apiResponse->getHeaderLine('X-Guzzle-Redirect-History');
$client = new Client();
$response = $client->request(
'POST', /*instead of POST, you can use GET, PUT, DELETE, etc*/
'https://api.sandbox.ebay.com/identity/v1/oauth2/token',
[
'headers' => [
'Content-Type'=>'application/x-www-form-urlencode',
'Authorization'=>'Basic '.base64_encode('<'.env('EBAY_CLENT_APP_ID').'>:<'.env('EBAY_CLENT_APP_SECRET').'>'),
],
'form_params' => [
'grant_type' => 'authorization_code',
'code' => $req->code,
'redirect_uri' => env('EBAY_REDIRECT_URI')
]
]
);
$output = json_decode($response->getBody());
dd($output);
I am using guzzlehttp 7.4 and laravel 8.65. All the credentials I am using is all sandbox so I am not sure what I am doing wrong. I keep getting the same error unsupported_grant_type etc.
I am learning Laravel Passport and developing an OAuth2 server. After creating a client I made the following call to get the authorization code
Route::get('/', function (Request $request) {
$request->session()->put('state', $state = Str::random(40));
$query = http_build_query([
'client_id' => <Client_Id>,
'redirect_uri' => 'http://<Consumer_App_URL>/callback',
'response_type' => 'code',
'scope' => '',
'state' => $state,
]);
return redirect('http://<OAuth2_Server_URL>/oauth/authorize?'.$query);
});
The call works as expected and I got the authorization code, however when redirecting to the callback route which is defined like so
Route::get('/callback', function (Request $request) {
$state = $request->session()->pull('state');
throw_unless(
strlen($state) > 0 && $state === $request->state,
InvalidArgumentException::class
);
$response = Http::asForm()->post('http://<OAuth2_Server_URL>/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => <Client_Id>,
'client_secret' => '<Cient_Secret>',
'redirect_uri' => 'http://consumer/callback',
'code' => $request->code,
]);
return $response->json();
});
It didn't work, the response instance is just null. I can't figure out what might be the issue.
So I finally solved the problem, I just have to run php artisan config:cache . [reference]
I am trying to get a response from the Metals API but keep getting 404 errors even though I can get the API using the URL.
public function valueFromApi(){
$accesskey = "123456";
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://metals-api.com/api/latest', [
'form_params' => [
'access_key' => $accesskey,
'base' => 'GBP',
'symbols' => 'XAU',]
]);
dd($response);
}
If I try and access the URL directly through a browser this works:
https://metals-api.com/api/latest?access_key=123456&base=GBP&symbols=XAU
I must have misunderstood the way the parameters are working. Any advice is appreciated.
Form params is not the same as query parameters. Therefor you need to set the parameters as query. If you are accessing this in the browser, i would not expect it to be a POST but a GET.
$response = $client->request('GET', 'https://metals-api.com/api/latest', [
RequestOptions::QUERY => [
'access_key' => $accesskey,
'base' => 'GBP',
'symbols' => 'XAU',
]
]);
I am using the RequestOptions, this is syntaxic sugar for the hardcoded string options, the same as 'query'.
As specified in their docs, you need to define the constant
define("form_params", GuzzleHttp\RequestOptions::FORM_PARAMS );
Then you can use your code
$response = $client->request('POST', 'https://metals-api.com/api/latest', [
'form_params' => [
'access_key' => $accesskey,
'base' => 'GBP',
'symbols' => 'XAU',]
]);
I have a phpleague/oauth2 server implementation, which is working fine, ie generating access/refresh tokens, validating etc.
I have a following problem. When I refresh the token with grant_type=refresh_token with console curl, I successfully get the new access_token, but when doing this with a test:
$I->sendPOST('access_token', [
'grant_type' => 'password',
'client_id' => '111',
'client_secret' => '222',
'username' => 'exampleuser',
'password' => 'examplepass',
]);
$I->seeResponseCodeIs(200);
$I->seeResponseContainsJson(['token_type' => 'Bearer']);
// I receive a proper string, checked that out
$token = $I->grabDataFromResponseByJsonPath('$.refresh_token')[0];
$I->sendPOST('access_token', [
'grant_type' => 'refresh_token',
'client_id' => 1,
'client_secret' => 'pass2',
'refresh_token' => $token
]);
$I->seeResponseCodeIs(200); // Here I receive 403
...
I repeat, doing this manually in terminal works fine.
After debugging it myself I found out that refresh token validation fails
at oauth2-server/src/Grant/RefreshTokenGrant.php at:
$refreshToken = $this->decrypt($encryptedRefreshToken);
But still I can't understand why it works manually. I did urlencode/urldecode and tons of var dumps, but still can't get the solution.