My app is vue spa backed by Laravel Api. I am using Laravel passport for authentication. in login controller it receives the username and password from the request, and adds the 'passport_client_id' and passport_cleint_secret' to the $request, and uses Guzzle to make a request to the '/oauth/token>' url. This works fine.
Then i proceeded to write a test to see if a user can login(i.e: that it receives a access_token). I am getting the following error
GuzzleHttp\Exception\ClientException: Client error: `POST http://localhost:8000/oauth/token` resulted in a `401 Unauthorized` response:
{"error":"invalid_client","error_description":"Client authentication failed","message":"Client authentication failed"}
I have checked if phpunit is missing any data, but it has all the data it needed. Interesting thing is if i make the same request from testclass, it does return a successful response.
My controller:
$http = new \GuzzleHttp\Client();
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
]
]);
return $response->getBody();
My test:
$this->artisan('passport:install');
$passport_client_secret = DB::table('oauth_clients')->where('id',2)->value('secret');
Config::set('services.passport.client_id', 2);
Config::set('services.passport.client_secret', $passport_client_secret);
$user = factory('App\User')->create();
$response = $this->json('post','api/v1/login',[
'username' => $user->email,
'password' => 'password'
]);
For debugging , i tried directly making the api request from testclass using the following code , it succeeds.
$response = $this->json('post',config('services.passport.login_endpoint'), [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $user->email,
'password' => 'password',
]);
Any idea why guzzle behaves different when used in PHPunit? What can i do to successfully test this controller?
Thanks in advance.