Coinbase Invalid 404 request OAuth2 Guzzle - php

I try make authorization in coinbase with OAuth2:
$client = new Client(['cookies' => true]);
try {
$response = $client->request('POST', $this->urlAccessToken, [
'headers' => [
'cache-control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'form_params' => [
'grant_type' => 'authorization_code',
'code' => $request->code,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'redirect_uri' => $this->redirectUri
]
]);
dd($response->getBody());
} catch (\Exception $e) {
return response($e->getMessage(), 400);
}
After authorization in coinbase him me redirect to redirect URI and when send request exchange code i see bad response:
Client error: POST http://www.coinbase.com/oauth/token resulted in a 404 Not Found response: Invalid request. Instead of a GET request, you should be making a POST with valid POST params. For more informat (truncated...)
All code which will authorize in Coinbase:
private $clientId;
private $clientSecret;
private $redirectUri;
private $urlAuthorize;
private $urlAccessToken;
public function __construct()
{
$this->clientId = env('COINBASE_CLIENT_ID');
$this->clientSecret = env('COINBASE_CLIENT_SECRET');
$this->redirectUri = route('oauth2-redirect');
$this->urlAuthorize = 'https://www.coinbase.com/oauth/authorize';
$this->urlAccessToken = 'http://www.coinbase.com/oauth/token';
}
public function oauth(Request $request)
{
$state = hash('sha256', $request->session()->getId());
if (!isset($request->code)) {
$parameters = [
'response_type' => 'code',
'client_id' => $this->clientId,
'redirect_uri' => $this->redirectUri,
'state' => $state
];
$authorizationUrl = $this->urlAuthorize . '?' . http_build_query($parameters);
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
} elseif (empty($request->state) || $request->state !== $state) {
return response('Invalid state', 400);
} else {
$client = new Client(['cookies' => true]);
try {
$response = $client->request('POST', $this->urlAccessToken, [
'headers' => [
'cache-control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'form_params' => [
'grant_type' => 'authorization_code',
'code' => $request->code,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'redirect_uri' => $this->redirectUri
]
]);
dd($response->getBody());
} catch (\Exception $e) {
return response($e->getMessage(), 400);
}
}
}
Also i checked it in postman and him return good response:
enter image description here

Problem was in URL access token, need use https://api.coinbase.com/oauth/token instead http://www.coinbase.com/oauth/token.

Related

"error": "invalid_grant", "error_description": "Bad Request" when i am trying to login with gmail

this is my get access token method
protected function getAccessToken($code)
{
$request = new \XLite\Core\HTTP\Request(static::TOKEN_REQUEST_URL);
$request->body = array(
'code' => $code,
'client_id' => $this->getClientId(),
'client_secret' => $this->getClientSecret(),
'redirect_uri' => $this->getRedirectUrl(),
'grant_type' => 'authorization_code',
);
$response = $request->sendRequest();
$accessToken = null;
if (200 == $response->code) {
$data = json_decode($response->body, true);
$accessToken = $data['access_token'];
}
return $accessToken;
}
and here i got the response in my logs:
[06:35:13.000000] array (
'request response from google' =>
(object) array(
'__CLASS__' => 'PEAR2\\HTTP\\Request\\Response',
'code' => 400,
'headers' =>
(object) array(
'__CLASS__' => 'PEAR2\\HTTP\\Request\\Headers',
'iterationStyle' => 'lowerCase',
'fields:protected' => 'Array(13)',
'camelCase:protected' => NULL,
'lowerCase:protected' => NULL,
),
'cookies' =>
array (
),
'body' => '{
"error": "invalid_grant",
"error_description": "Bad Request"
}',
'scheme' => 'https',
'host' => 'accounts.google.com',
'path' => '/o/oauth2/token',
'uri' => 'https://accounts.google.com/o/oauth2/token',
'port' => 443,
),
)
you can see the in response body if you required any thing else let me know
The post body is sent as a query string not an array
POST https://accounts.google.com/o/oauth2/token
code=AuthorizationCode&client_id=ClientId}&client_secret={ClientSecret}&redirect_uri=RedirectURI&grant_type=authorization_code
remember the code will expire in five minutes and can only be used once.
I beleave in php you should be using http-build-query for your post data.

Laravel Passport - oauth/token gives Client authentication failed

I've installed Laravel Passport.
Here is how I generate auth code:
public function auth(Request $request)
{
$request->session()->put('state', $state = Str::random(40));
$request->session()->put(
'code_verifier', $code_verifier = Str::random(128)
);
$codeChallenge = strtr(rtrim(
base64_encode(hash('sha256', $code_verifier, true))
, '='), '+/', '-_');
$query = http_build_query([
'client_id' => '1',
'redirect_uri' => 'http://127.0.0.1:8000/authorize/response',
'response_type' => 'code',
'scope' => '',
'state' => $state,
'code_challenge' => $codeChallenge,
'code_challenge_method' => 'S256',
]);
return redirect('http://127.0.0.1:9000/oauth/authorize?'.$query);
}
Above request all passes well.
Here is how I try to generate access token:
public function authResponse(Request $request)
{
$state = $request->session()->pull('state');
throw_unless(
strlen($state) > 0 && $state === $request->state,
InvalidArgumentException::class
);
$response = Http::asForm()->post('http://127.0.0.1:9000/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => '1',
'client_secret' => 'hYMELQ1VKAWrG0TwrkM3JxUuoICSCWCzCztClZZi',
'redirect_uri' => 'http://127.0.0.1:8000/authorize/response',
'code' => $request->code,
]);
return $response->json();
}
When I execute the code for generating the access token I get the following error:
{"error":"invalid_client","error_description":"Client authentication
failed","message":"Client authentication failed"}
Any idea what can be the cause of this error? I've taken the client_secret from the DB.
Any idea what can be the problem and how can I fix it?
You are missing to pull from session the code_verifier on your authResponse() method.
$codeVerifier = $request->session()->pull('code_verifier');
Then add the $codeVerifier to the 'code_verifier' in post method when your are converting authorization codes to access tokens.
$response = Http::asForm()->post('http://127.0.0.1:9000/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => '1',
'client_secret' => 'hYMELQ1VKAWrG0TwrkM3JxUuoICSCWCzCztClZZi',
'redirect_uri' => 'http://127.0.0.1:8000/authorize/response',
'code' => $request->code,
]);
Check out the docs about this.

Laravel problem with parameter in GuzzleHttp

Hello
When I use GuzzleHttp\Client is working fine but form_params not working but It was working with me in another project but this project no params working with me when I send it in form_params
Guzzle Code working
$http = new Client;
try {
$response = $http->post('https://smsmisr.com/api/webapi/?username='.$this->username.'&password='.$this->password.'&language=1&sender='.$this->sender.'&mobile=XXXX&message=Hello&DelayUntil='.Carbon::now()->toDateTimeString());
// retrun json_decode((string)) $response->getBody(), true);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if($e->getCode() === 400) {
return response()->json('Invalid Request.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your username and passowrd are incorrect', $e->getCode());
}
return response()->json('Something went wrong on the server', $e->getCode());
}
Guzzle Code not working
the code no sends any form_params yet.
$response = $http->post($this->link, [
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
],
'form_params' => [
'username' => $this->username,
'password' => $this->password,
'sender' => $this->sender,
'language' => 1,
'mobile' => 'XXXXXXX',
'message' => 'Hello guys',
'DelayUntil' => Carbon::now()->toDateString()
]
]);
This problem in my Vuejs too when using Axios I should make
s
ubmitForm(context, data) {
const params = {
...data
}
return new Promise((resolve, reject) => {
axios.post(`${data.post.apiURL}`, params)
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
})
})
},
I testing on PostMan.
From the docs here
form_params cannot be used with json:
form_params cannot be used with the multipart option. You will need to use one or the other. Use form_params for application/x-www-form-urlencoded requests, and multipart for multipart/form-data requests.
This option cannot be used with body, multipart, or json
Try this bro, change "form_params" to "json"
$response = $http->post($this->link, [
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
],
'json' => [
'username' => $this->username,
'password' => $this->password,
'sender' => $this->sender,
'language' => 1,
'mobile' => 'XXXXXXX',
'message' => 'Hello guys',
'DelayUntil' => Carbon::now()->toDateString()
] ]);

API error no parameters when there are parameters given

This is the error I'm getting, as you can see there is a parameter in the URL, but the error says there weren't any parameters given. Can anbody help me out?
Client error: PUT https://webapi.teamviewer.com/api/v1/devices/d38237721?alias=laptop-test resulted in a 400 Bad Request response:
{"error":"invalid_request","error_description":"no parameters were given.","error_code":1}
This is my code
public function update($device_id, $options)
{
$token = 'thereisatokenhere';
$client = new Client(['base_uri' => 'https://webapi.teamviewer.com/api/v1/']);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept-Language' => 'en-US',
'Content-Type' => 'application/json'
];
$response = $client->request('PUT', 'devices/' . $options['device_id'], [
'headers' => $headers,
'form_params' => [
'alias' => $options['alias'],
],
]);
$response = json_decode($response->getBody()->getContents(), true);
$deviceIdsAPI = $response['devices'];
return $deviceIdsAPI;
}
2nd
$request = new Request('PUT', 'https://webapi.teamviewer.com/api/v1/devices/' . $options['device_id'], ['alias' => $options['alias']]);
$response = $client->send($request, ['timeout' => 2, 'headers' => $headers]);
Here is an example of a PUT request in Guzzle:
$client->put('devices/' . $options['device_id'], [
'body' => [
'alias' => $options['alias'],
'other_field' => '123'
],
'headers' => $headers,
'allow_redirects' => false,
'timeout' => 5
]);
Update:
In the latest version (Guzzle 6) it should be like this:
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http://httpbin.org/put', ['test' => '123']);
$response = $client->send($request, ['timeout' => 2, 'headers' => $headers]);
See this answer and here is the official Guzzle documentation

Bearer Token in Guzzle HTTP 6.1 not working

I have a problem with my Bearer-Authorization in Guzzle-HTTP.
I use it to test my PHP-REST-API with PHPUnit.
here is my test method:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = $responseJson->data->token;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
But if I set the token hard coded like this:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE0NjQ5NzExMzQsImp0aSI6IjByR3FpOW15Rm1rRGo2TU9sMVhkK3dRU3p1V0pWejM1UEhiU2dTMmg5SEU9IiwiaXNzIjoiQXBwTmFtZSIsIm5iZiI6MTQ2NDk3MTE0NCwiZXhwIjoxNDY0OTczMTQ0LCJzdWIiOiJ0ZXN0QG1haWwuZGUifQ.yA4a_S6ILCeqENm00H712g9uF5g9eSz_BmnaMDdZ2r4p5e1q88g0T09IG2WKCi1oExoBfQ8VTmKeX6ZQv0RydQ;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
and also with Postman, it is working.
It's the same token which I receive from my REST-API.
Do you have any ideas what's wrong?

Categories