I am new in Laravel Passport and installed and configured with official documentation.
public function register(){
$password = Hash::make('demo');
$user = DB::table('users')->insertGetId([
'name' => 'User',
'email' => 'userdev#gmail.com',
'password' => $password,
]);
// create oauth client
$oauth_client = \App\OauthClient::create([
'user_id' => $user,
'name' => 'User',
'secret' => base64_encode(hash_hmac('sha256',$password, 'secret', true)),
'password_client' => 1,
'personal_access_client' => 0,
'redirect' => '',
'revoked' => 0,
]);
$response = ['status'=>200,'message'=>'Successfully Registered'];
return $response;
I just run the API throgh postman and its getting response as Successfully Registered
After that I just called the http://localhost/passport/oauth/token route to authenticate the user. But its not working. Its returning like..
Postdata :
grant_type:password
client_id :1
client_secret:j7q0ky8chHQ0RHJFpWo4Lqn/hl7Z0ntzYeyzsXE9ULA=
username:userdev#gmail.com
password:demo
scope:
Response :
{
"error": "invalid_request",
"message": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.",
"hint": "Check the `client_id` parameter"
}
Make sure it is placed in body not in params.
Still not sure why, but running php artisan config:clear fixed this for me.
Related
i'm creating an authentication api using passport from the official docs but i'm stuck on sending GuzzelHttp request
i'v done exactly like the docs but when i want to test with postman no result returned it just stay loading without end
this is my code
my controller
$user = new User();
$user->email = $request->email;
$user->name = $request->name;
$user->password = bcrypt($request->password);
$user->save();
$http = new Client;
$response = $http->post('http://localhost:8000/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'x2ESrkADoQEaQ91iMW9kKiIvjKo0LL4RxlUtqtmy',
'password' => $request->password
],
]);
dd($response);
return response([
'success'=> true,
'successMessageKey' => 'userCreatedSuccessfully' ,
'data'=>json_decode((string) $response->getBody(), true)
]);
and my route
Route::post('users/register',[
'uses' => 'Api\AuthController#register'
]);
and when i run my route i got no result like this and stuck in loading
The issue is when using php artisan serve, it uses a PHP server which is single-threaded.
The web server runs only one single-threaded process, so PHP applications will stall if a request is blocked.
You can do this solution:
When making calls to itself the thread blocked waiting for its own reply. The solution is to either seperate the providing application and consuming application into their own instance or to run it on a multi-threaded webserver such as Apache or nginx.
Or if you are looking for a quick fix to test your updates - you can get this done by opening up two command prompts. The first would be running php artisan serve (locally my default port is 8000 and you would be running your site on http://localhost:8000). The second would run php artisan serve --port 8001.
Then you would update your post request to:
$response = $http->post('http://localhost:8001/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'x2ESrkADoQEaQ91iMW9kKiIvjKo0LL4RxlUtqtmy',
'password' => $request->password
],
]);
This should help during your testing until you are able to everything on server or a local virtual host.
Try including password_confirmation in your parameters in Postman. That's what I did in my laravel passport project
I findout the problem in your code
please check the parameter which you sent to auth/token. username is missing in your request
You need pass array of form_params as json
e.g
$response = $http->post('http://localhost:8000/oauth/token', [
'form_params' => json_encode([
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'x2ESrkADoQEaQ91iMW9kKiIvjKo0LL4RxlUtqtmy',
'password' => $request->password
]),
]);
Im using Laravel passport for API authentication. I have two routes
/api/login
and
/oauth/token
Since I cannot hardcode my client id and the login receives from JS and the params and client id is hardcoded inside a login method(laravel), Im trying to post the values using Guzzle (6.0) to oauth/token (POST requests).
I followed a youtube video and there it works but not mine. Iam using 5.6, not sure which version was in the video. Could someone help?
Below is the Video
https://www.youtube.com/watch?v=HGh0cKEVXPI&t=838s
Below is the code
$http = new GuzzleHttp\Client();
$request = $http->post(URI, '/oauth/token', [
'form_params' => [
'username' => 'bar',
'password' => 'xxxxxx',
'client_id' => 2,
'grant_type' => 'password',
'client_secret' => '00000000000000000'
]
]);
return $request;
You are not getting the response only returning guzzle $request initalization so add getBody()
$http = new GuzzleHttp\Client();
$request = $http->post(URI, '/oauth/token', [
'form_params' => [
'username' => 'bar',
'password' => 'xxxxxx',
'client_id' => 2,
'grant_type' => 'password',
'client_secret' => '00000000000000000'
]
]);
return $request->getBody();
I think you are trying to request in build-in server.
So You try two servers to send the request.
It will be working.
Like localhost:8000 and localhost:9000 server
Use this command
php artisan serve
php artisan serve --port=9000
Thanks.
You should check the status first to make sure that everything is okay by using
$request->getStatusCode();
You can get your response by
$request->getBody();
you can see also full documentation of using GuzzulHttp from Here
http://docs.guzzlephp.org/en/stable/
Laravel Passport Auth Stuck when run on self server and client in same project for password based token authentication
LoginController
public function authenticaterrr(Request $request)
{
$http = new Client();
try{
//dd("Hello");
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
// 'username' => $request->get('username'),
// 'password' => $request->get('password'),
'username' => 'xxxxxx#xxxxx.com',
'password' => 'xxxxx',
'scope' => '*',
],
]);
// $apiResponse = json_decode((string) $response->getBody(), true);
// dd($apiResponse);
$apiResponse = json_decode((string) $response->getBody(), true);
dd($apiResponse);
session(['api'=> $apiResponse]);
session(['api-token'=> $apiResponse['access_token']]);
return json_decode($response->getBody(), true);
}catch (ClientException $exception){
dd("Hello");
return json_decode($exception->getResponse()->getBody(), true);
}
}
IN Web.php
Route::get('/auth/api/validate', 'Auth\LoginController#authenticaterrr');
In PostMan It didn't Get and Stuck Here is Output
If i will create new Project and Use that than it will work for me so what would be solution to run in same project
If you're running your web app on the built-in PHP server / php artisan serve, then the second auth/token Passport request "kills" the first authenticaterrr HTTP request.
This is because the built-in PHP server is single threaded.
Kudos/credits to this comment.
https://stackoverflow.com/a/51010186/8735680
function tokenRequest(Request $request){
$request->request->add([
"grant_type" => "password",
"username" => $request->username,
"password" => $request->password,
"client_id" => "x",
"client_secret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
]);
$tokenRequest = $request->create(
env('APP_URL').'/oauth/token',
'post'
);
$instance = Route::dispatch($tokenRequest);
return json_decode($instance->getContent());
}
The following code works perfectly fine when you are calling your own routes/code inside project. Try this because it don't require Guzzle or curl or any other additional package.
/**
* Checking for server side OAuth authentication
* Place this code in controller where you are performing authorization
* #return Object
*/
public function checkOAuth(Request $req){
try{
$req->request->add([
"grant_type" => "password",
"client_id" => config('services.passport.client_id'), //Get from oauth_clients table
"client_secret" => config('services.passport.client_secret'), //Get from oauth_clients table
"username" => $req->username,
"password" => $req->password,
]);
$tokenRequest = $req->create(
config('services.passport.login_endpoint'), //'YOUR_APP_URL/oauth/token'
'post'
);
$instance = \Route::dispatch($tokenRequest);
return json_decode($instance->getContent());
}
catch(Exception $e){
dd($e->getMessage());
}
}
this will return the ttl, refresh_token and access_token. Use as per your requirements.
Using Laravel 5 and trying to send some data from my site to another one, which provides me with the REST API. But they use cookies as a authorization. For this moment, I've passed auth successfully. And stuck on how should I send this cookie to API interface via POST method? Here is my listing.
Thanx in advance.
P.S. All things are going on inside the controller.
if (Cookie::get('amoauth') !== null) {
//COOKIE IS HERE
$client = new Client();
$newlead = $client->post('https://domain.amocrm.ru/private/api/v2/json/leads/set', [
'add' => [
'add/name' => 'TEST LEAD',
'add/date_create' => time(),
'add/last_modified' => time(),
'add/status_id' => '1',
'add/price' => 5000
]
]);
} else {
$client = new Client();
$auth = $client->post('https://domain.amocrm.ru/private/api/auth.php',[
'USER_LOGIN' => 'login',
'USER_HASH' => 'hash',
'type' => 'json'
]);
$auth = $auth->getHeaders('Set-Cookie');
Cookie::queue('amoauth', $auth, 15);
return redirect('/test');
}
Now it returns me the following:
Client error: `POST https://domain.amocrm.ru/private/api/v2/json/leads/set` resulted in a `401 Unauthorized` response.
Found the solution: switched to ixudra/curl.
I have an API I'm building with Lumen 5.3. For Authentication I'm using Laravel Passport (ported to Lumen via the dusterio/lumen-passport package).
All works well in Postman, and all tests pass fine with a single request.
However once I make a test that has multiple requests I get the error: 'Auth guard driver [api] is not defined'. The guard is defined in my auth config, and as I said works perfect outside of this test case.
Example test:
public function it_requires_users_password_when_updating_email(ApiTester $I)
{
$I->wantTo('Require password when updating email');
$user = factory(\App\User::class)->create();
$I->sendPOST('oauth/token', [
'grant_type' => 'password',
'client_id' => 1,
'client_secret' => env('OAUTH_SECRET'),
'username' => $user->email,
'password' => 'password',
'scope' => ''
]);
$token = $I->grabDataFromResponseByJsonPath('$.access_token')[0];
$I->amBearerAuthenticated($token);
$I->sendPUT('users/' . $user->id, ['email' => 'bender.rodriguez#planetexpress.com']);
$I->seeResponseCodeIs(422);
$I->seeRecord('users', array_only($user->toArray(), ['id', 'email']));
$I->dontSeeRecord('users', ['id' => $user->id, 'email' => 'bender.rodriguez#planetexpress.com']);
$I->sendPUT('users/' . $user->id, ['email' => 'bender.rodriguez#planetexpress.com', 'password' => 'password']);
$I->seeResponseCodeIs(200);
$I->seeRecord('users', ['id' => $user->id, 'email' => 'bender.rodriguez#planetexpress.com']);
}
The test passes fine if I remove the last 3 lines (everything from the 2nd sendPUT request), but once I include that, I get the error.
Any ideas?