Unable to generate Google OAuth 2 token - laravel-5

I am trying to generate Google OAuth 2 token using GuzzleHttp on a laravel application but I am getting this error message -
Client error: `POST https://accounts.google.com/o/oauth2/token` resulted in a `400 Bad Request` response: { "error": "invalid_grant", "error_description": "Bad Request" }
Here is my code
$client = new Client();
$call = $client->post(env('AUTH_URL'), [
'form_params' => [
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'redirect_uri' => env('CALLBACK_URL'),
'grant_type' => 'authorization_code',
'scope' => env('SCOPE'),
'code' => env('AUTH_CODE')
]
]);
$response = json_decode($call->getBody()->getContents(), true);
dd($response);
Please what might be the problem here?

Related

Using Guzzle in Laravel with POST

I want to send a POST request to an external API
Here is my method to call
public function recursub(Request $request) {
$users = User::where('cancel_trial', 1)->get();
foreach($users as $user) {
//dd($user->email);
$url= 'https://api.paystack.co/subscription';
$client = new Client();
$response = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer sk_test_0994##############',
],
'form_params' => [
'customer' => '233########',
'plan' => 'PLN_###########',
]
]);
dd($response->getBody());
//dd($response->getBody()->getContents());
}
}
But I keep getting this error when I call the endpoint
GuzzleHttp \ Exception \ ClientException (400)
Client error: POST https://api.paystack.co/subscription resulted in a 400 Bad Request response: { "status": false, "message": "Request body could not be parsed. Make sure request body matches specified content-ty (truncated...)
It's looks like that you send wrong request to API.
If you set application/json maybe you should pass parameter in body, not in form params:
$response = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer sk_test_0994##############',
],
'body' => json_encode([
'customer' => '233########',
'plan' => 'PLN_###########',
])
]);
Another information that maybe can be helpful is that you can disable exception with ['http_errors' => false] option (http://docs.guzzlephp.org/en/stable/request-options.html#http-errors).

getting invalid_credentials on laravel-passport-social-grant package

Package used is the : https://github.com/coderello/laravel-passport-social-grant
I have followed all the expected changed with the tutorial provided at :
https://medium.com/#hivokas/api-authentication-via-social-networks-for-your-laravel-application-d81cfc185e60
url :
http://myurl.com/oauth/token
output:
{
"error": "invalid_credentials",
"error_description": "The user credentials were incorrect.",
"message": "The user credentials were incorrect."
}
parameter have used with the postman is as followed:
grant_type' => 'social', // static 'social' value
'client_id' => $clientId, // client id
'client_secret' => $clientSecret, // client secret
'provider' => $providerName, // name of provider (e.g., 'facebook', 'google' etc.)
'access_token' => $providerAccessToken, // access token issued by specified provider
],
what can be the issue here ?
For Facebook you need to have the client_id and secret, in your services.php
Code inside FacebookProvider of Socialite
protected function getUserByToken($token)
{
$this->lastToken = $token;
$params = [
'access_token' => $token,
'fields' => implode(',', $this->fields),
];
if (! empty($this->clientSecret)) {
$params['appsecret_proof'] = hash_hmac('sha256', $token, $this->clientSecret);
}
$response = $this->getHttpClient()->get($this->graphUrl.'/'.$this->version.'/me', [
'headers' => [
'Accept' => 'application/json',
],
'query' => $params,
]);
return json_decode($response->getBody(), true);
}
So, google kinda works without secret.

Unable to Authorize Or Get Token

I am having trouble getting a laravel application to access an api endpoint in another laravel app, same server. I can get it to work in terminal, and postman but not from the laravel app itself, both getting an auth token and using work in p;ostman and terminal but not in laravel. (killing me that this was working the other day)
I have tried many Guzzle and curl configs, Using WAMP on Win 10. Laravel Framework version 5.3.31, PHP 7.2.18
try {
$response = $http->request('POST',$this->base_oauth_url. 'oauth/token', [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded',
],
'form_params' => [
'grant_type' => 'password',
'client_id' => self::API_CLIENT_ID,
'client_secret' => self::API_SECRET,
'username' => self::API_USERNAME,
'password' => self::API_PASSWORD,
'scope' => '*',
],
'debug'=>$this->debug,
'allow_redirects' => false,
'verify' => false,
]);
} catch (ClientException $e) {
throw new Exception("Guzzle Error: {$e->getMessage()}");
} catch (Exception $e) {
throw new Exception("Send Error: ({$e->getCode()}): {$e->getMessage()}");
}
$response = json_decode((string) $response->getBody()->getContents());
$data = array();
$data['access_token'] = $response->access_token;
$data['refresh_token'] = $response->refresh_token;
Error:
Guzzle Error: Client error: POST http://mytestdomain.com/oauth/token resulted in a 401 Unauthorized response:
{"error":"invalid_client","message":"Client authentication failed"}

Retrieving Client Credentials grant token returns 401 Unauthorized

I'm setting up Laravel Passport's Client Grant and using Guzzle to retrieve a token, but I'm getting a 401 Unauthorized error.
I created the client using: php artisan passport:client --client.
The client generated is:
Client ID: 1
Client secret: NmJsEVFClXVqWJuQnZTWA3bnZEVZ0KaC13anHZt1
I saved these in my .env file and ran the command
php artisan config:clear
Here's my code:
$url = 'http://hub.local/oauth/token';
$client_secret = env('CLIENT_SECRET');
$client_id = env('CLIENT_ID');
$client = new Client();
try {
$response = $client->post($url, [
'json' => [
'grant_type' => 'client_credentials',
'client_id' => $client_id,
'client_secret' => $client_secret,
],
'headers' => [
'Content-Type' => 'application/json',
],
]);
return $response;
} catch (RequestException $e) {
dd($e);
} catch (Exception $e) {
dd($e);
}
And the resulting error message:
ClientException {#660 ▼
-request: Request {#649 ▶}
-response: Response {#657 ▶}
-handlerContext: []
#message: """
Client error: `POST http://hub.local/oauth/token` resulted in a `401 Unauthorized` response:
{"error":"invalid_client","error_description":"Client authentication failed","message":"Client authentication failed"}
"""
#code: 401
#file: "C:\repos\client\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php"
#line: 113
When I try the request using the same parameters and values in Insomnia, the request works.
Seems I can't post images yet.
https://i.imgur.com/w6Ollin.jpg
https://imgur.com/fXpzKjj.jpg
I'm using Laravel 5.8.12, Guzzle 6.3.3 and Passport 7.2.2.
What am I missing?
Update: The problem only occurred when I was running the ( Laravel) client and server instances on the same local xampp server. I separated them to run on their own individual xampp instances and the authentication worked without issue. What had confused me while testing solely locally was that the request worked with Insomnia, but not the browser. I'm assuming that the "machine to machine" part of this client grant was seeing my client + server sharing the same xampp instance as something unrecognized. In any event, there's no actual problem. Hopefully this helps someone else.
in laravel doc there is an example like this :
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'redirect_uri' => 'http://example.com/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});
when I tested this one with my info I changed to some thing like this :
Route::get('/users/login', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://payment.devenv/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'z8YWlJeaW0d7o7SFyPLISUxYOcO5CxjGrZ5YuItl',
'username' => 'athamidn#gmail.com',
'password' => '123456',
'scope' => '',
'code' => 200,
'redirect_uri' => 'http://example.com/callback',
],
]);
return json_decode((string) $response->getBody(), true);
});
And I received an error same with your error. After many hours I got issue :
In database at oauth_clients table this is my info :
2 name: Laravel Password Grant Client redirect: http://localhost
when I changed redirect url to this it works.
finally :
Route::get('/users/login', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://payment.devenv/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'z8YWlJeaW0d7o7SFyPLISUxYOcO5CxjGrZ5YuItl',
'username' => 'athamidn#gmail.com',
'password' => '123456',
'scope' => '',
'code' => 200,
'redirect_uri' => 'http://localhost'
],
]);
return json_decode((string) $response->getBody(), true);
});
I believe you can re-create passport public and private keys stored in /storage folder by executing the php artisan passport:install. Then you can define those keys in the .env file and pass it with client_id & client_secret.
command output
Personal access client created successfully.
Client ID: 31
Client secret: xxxx
Password grant client created successfully.
Client ID: 32
Client secret: xxxx
/.env
PERSONAL_CLIENT_ID=31
PERSONAL_CLIENT_SECRET=xxxx
PASSWORD_CLIENT_ID=32
PASSWORD_CLIENT_SECRET=xxxx
POST - API parameters - /oauth/token
'client_id' => env('PASSWORD_CLIENT_ID'),
'client_secret' => env('PASSWORD_CLIENT_SECRET')
This error could happen when those private and public keys are not matched properly with the already created ones.
Cheers!

Generate laravel passport tokens internally. 401 error unauthorized

I'm trying to create a bearer token for passport so I can use my api routes internally. I send a post request to /oauth/token with the client id and client secret. The code that generates the bearer token looks like this.
public function generateToken() {
try {
$req = Request::create('/oauth/token', 'POST', [
'grant_type' => 'client_credentials',
'client_id' => '1',
'client_secret' => 'POe81tKvmZ0DhBdtwdM7VPoV5tTKobVYzSc9A0RX',
'scope' => '*',
]);
$res = app()->handle($req);
return $res;
} catch (Exception $e){
log::critical('Failed to generate bearer token.');
} catch (error $e) {
log::critical('Failed to generate bearer token.');
}
}
However when trying to do this request I get a 401 authorised.
#content: "{"error":"invalid_client","message":"Client authentication failed"}" #version: "1.1"#statusCode: 401 #statusText: "Unauthorized"
Is there anyway of fixing this?
This works for me
$client = new client(['verify' => false]);
$response = $client->post($url, [
'form_params' => [
'client_id' => 5,
// The secret generated when you ran: php artisan passport:install
'client_secret' => 'HxLB5LVi3HhHxYkoHVZinoYUz5Ab3HnbWmiB1KBd',
'grant_type' => 'client_credentials',
'scope' => '*',
]
]);

Resources