Laravel Passport - Testing Password GrantHow do I test a private function or a class that has private methods, fields or inner classes?Secure hash and salt for PHP passwordsLaravel Passport Error - ServerException in RequestException.php line 107Laravel 5.3 Password Grant Tokens [user credentials incorrect]How to limit user actions with Laravel Passport Scopes + Password Grant TypeGet authenticated user with Laravel Passport and grant passwordLaravel Passport APi - Implicit grantLaravel 5.5 - Laravel Passport Correct Grant Type To Use?How to use Laravel Passport with Password Grant Tokens?MethodNotAllowedException Laravel Password Grant API

Does the Freedom of Movement spell prevent petrification by the Flesh to Stone spell?

How to run a command 1 out of N times in Bash

Modeling an M1A2 Smoke Grenade Launcher

How did the Altair 8800 front panel load the program counter?

Does the telecom provider need physical access to the SIM card to clone it?

In Toy Story, are toys the only inanimate objects that become alive? And if so, why?

Calculate Landau's function

Can authors email you PDFs of their textbook for free?

Can a system of three stars exist?

Turn off Google Chrome's Notification for "Flash Player will no longer be supported after December 2020."

Why does the U.S. military maintain their own weather satellites?

My colleague treats me like he's my boss, yet we're on the same level

What is the practical impact of using System.Random which is not cryptographically random?

Why do presidential pardons exist in a country having a clear separation of powers?

What are ways to record who took the pictures if a camera is used by multiple people?

Where should I draw the line on follow up questions from previous employer

Is it good practice to speed up and slow down where not written in a song?

'spazieren' - walking in a silly and affected manner?

How can I portray a character with no fear of death, without them sounding utterly bored?

Large intervals in score in Bach

Can a pet cat attune to a magical item?

Can two aircraft be allowed to stay on the same runway at the same time?

Am I required to correct my opponent's assumptions about my morph creatures?

Could a simple hospital oxygen mask protect from aerosol poison?



Laravel Passport - Testing Password Grant


How do I test a private function or a class that has private methods, fields or inner classes?Secure hash and salt for PHP passwordsLaravel Passport Error - ServerException in RequestException.php line 107Laravel 5.3 Password Grant Tokens [user credentials incorrect]How to limit user actions with Laravel Passport Scopes + Password Grant TypeGet authenticated user with Laravel Passport and grant passwordLaravel Passport APi - Implicit grantLaravel 5.5 - Laravel Passport Correct Grant Type To Use?How to use Laravel Passport with Password Grant Tokens?MethodNotAllowedException Laravel Password Grant API






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm using Laravel 5.7 along with Passport to create an API for a first-party client. I have a login form that accepts the user's email and password and sends both to a custom LoginController. The LoginController then creates an oAuth payload, sends a POST request to oauth/token via Guzzle and returns the access_token, refresh_token and everything else to my first-party client.



Everything works perfectly when I test it in the browser. However I would now like to write an integration test for all of this and am running into an issue. The issue being that the oAuth server keeps rejecting my client and/or Guzzle request, only during testing.



Here is my corresponding code:



LoginController



<?php

namespace AppHttpControllersApi;

use AppDomainAuthPasswordGrant;
use AppHttpRequestsLoginRequest;

class LoginController extends ApiController

/**
* LoginController constructor.
*/
public function __construct()

$this->middleware('api')->only('login');


/**
* Attempt to authenticate the user with the credentials they provided
* and if successful, return an access token for the user.
*
* @param LoginRequest $request
* @return IlluminateHttpResponse
*/
public function login(LoginRequest $request)

return PasswordGrant::attempt($request->email, $request->password);




PasswordGrant



<?php

namespace AppDomainAuth;

use GuzzleHttpClient as GuzzleHttp;
use GuzzleHttpExceptionClientException;
use LaravelPassportClient;

class PasswordGrant

/**
* The GuzzleHttp client instance.
*
* @var GuzzleHttp
*/
protected $http;

/**
* PasswordGrant constructor.
*
* @param GuzzleHttp $http
*/
public function __construct(GuzzleHttp $http)

$this->http = $http;


/**
* @param $username
* @param $password
* @return IlluminateHttpResponse
*/
public static function attempt($username, $password)

$passwordGrant = resolve(static::class);

$payload = $passwordGrant->oAuthPayload(
$passwordGrant->oAuthClient(), $username, $password
);

return $passwordGrant->oAuthResponse($payload);


/**
* Get the oAuth Client we are using to authenticate our login and user.
*
* @return Client
*/
protected function oAuthClient()

return Client::query()
->where('name', config('api.password_client'))
->where('password_client', true)
->where('revoked', false)
->firstOrFail();


/**
* The payload we need to send to our oAuth server in order to receive
* a bearer token and authenticate the user.
*
* @param Client $client
* @param $username
* @param $password
* @return array
*/
protected function oAuthPayload(Client $client, $username, $password)

return [
'form_params' => [
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $username,
'password' => $password,
'scope' => '*'
]
];


/**
* Get the response from our oAuth server.
*
* @param array $payload
* @return IlluminateHttpResponse
*/
protected function oAuthResponse(array $payload)

try

return $this->http->post(route('passport.token'), $payload)->getBody();

catch (ClientException $exception)

return response($exception->getMessage(), $exception->getCode());






PasswordGrantTest



<?php

namespace TestsFeatureRequestsTeam;

use AppDomainAuthPasswordGrant;
use AppModelsUser;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateSupportFacadesArtisan;
use TestsTestCasesTestCase;

class PasswordGrantTest extends TestCase

use RefreshDatabase;

/** @test */
public function it_returns_an_access_token_for_a_user_with_valid_credentials()

Artisan::call('passport:client', [
'--password' => true,
'--name' => config('api.password_client')
]);

$user = create(User::class);

$result = PasswordGrant::attempt($user->email, 'secret');

dd($result);




The dd at the end of my test always returns a 401 with the message:
"error":"invalid_client","message":"Client authentication failed"



I have triple checked the existence and validity of my user model, the passport client and made sure the payload is well-formed.



Why does the password grant work when I test it via the browser but it does not work when making the same request to the server from my tests?



Perhaps I am missing certain headers in my request to the server during testing?










share|improve this question
























  • The client_id field is supposed to contain an integer, however I am not sure if your function oAuthClient() returns an integer. Mostly eloquent functions return strings / collections. So check if the value passed to client_id is of type integer / i.e., without quotes.

    – Hari Harker
    Apr 6 at 20:35

















0















I'm using Laravel 5.7 along with Passport to create an API for a first-party client. I have a login form that accepts the user's email and password and sends both to a custom LoginController. The LoginController then creates an oAuth payload, sends a POST request to oauth/token via Guzzle and returns the access_token, refresh_token and everything else to my first-party client.



Everything works perfectly when I test it in the browser. However I would now like to write an integration test for all of this and am running into an issue. The issue being that the oAuth server keeps rejecting my client and/or Guzzle request, only during testing.



Here is my corresponding code:



LoginController



<?php

namespace AppHttpControllersApi;

use AppDomainAuthPasswordGrant;
use AppHttpRequestsLoginRequest;

class LoginController extends ApiController

/**
* LoginController constructor.
*/
public function __construct()

$this->middleware('api')->only('login');


/**
* Attempt to authenticate the user with the credentials they provided
* and if successful, return an access token for the user.
*
* @param LoginRequest $request
* @return IlluminateHttpResponse
*/
public function login(LoginRequest $request)

return PasswordGrant::attempt($request->email, $request->password);




PasswordGrant



<?php

namespace AppDomainAuth;

use GuzzleHttpClient as GuzzleHttp;
use GuzzleHttpExceptionClientException;
use LaravelPassportClient;

class PasswordGrant

/**
* The GuzzleHttp client instance.
*
* @var GuzzleHttp
*/
protected $http;

/**
* PasswordGrant constructor.
*
* @param GuzzleHttp $http
*/
public function __construct(GuzzleHttp $http)

$this->http = $http;


/**
* @param $username
* @param $password
* @return IlluminateHttpResponse
*/
public static function attempt($username, $password)

$passwordGrant = resolve(static::class);

$payload = $passwordGrant->oAuthPayload(
$passwordGrant->oAuthClient(), $username, $password
);

return $passwordGrant->oAuthResponse($payload);


/**
* Get the oAuth Client we are using to authenticate our login and user.
*
* @return Client
*/
protected function oAuthClient()

return Client::query()
->where('name', config('api.password_client'))
->where('password_client', true)
->where('revoked', false)
->firstOrFail();


/**
* The payload we need to send to our oAuth server in order to receive
* a bearer token and authenticate the user.
*
* @param Client $client
* @param $username
* @param $password
* @return array
*/
protected function oAuthPayload(Client $client, $username, $password)

return [
'form_params' => [
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $username,
'password' => $password,
'scope' => '*'
]
];


/**
* Get the response from our oAuth server.
*
* @param array $payload
* @return IlluminateHttpResponse
*/
protected function oAuthResponse(array $payload)

try

return $this->http->post(route('passport.token'), $payload)->getBody();

catch (ClientException $exception)

return response($exception->getMessage(), $exception->getCode());






PasswordGrantTest



<?php

namespace TestsFeatureRequestsTeam;

use AppDomainAuthPasswordGrant;
use AppModelsUser;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateSupportFacadesArtisan;
use TestsTestCasesTestCase;

class PasswordGrantTest extends TestCase

use RefreshDatabase;

/** @test */
public function it_returns_an_access_token_for_a_user_with_valid_credentials()

Artisan::call('passport:client', [
'--password' => true,
'--name' => config('api.password_client')
]);

$user = create(User::class);

$result = PasswordGrant::attempt($user->email, 'secret');

dd($result);




The dd at the end of my test always returns a 401 with the message:
"error":"invalid_client","message":"Client authentication failed"



I have triple checked the existence and validity of my user model, the passport client and made sure the payload is well-formed.



Why does the password grant work when I test it via the browser but it does not work when making the same request to the server from my tests?



Perhaps I am missing certain headers in my request to the server during testing?










share|improve this question
























  • The client_id field is supposed to contain an integer, however I am not sure if your function oAuthClient() returns an integer. Mostly eloquent functions return strings / collections. So check if the value passed to client_id is of type integer / i.e., without quotes.

    – Hari Harker
    Apr 6 at 20:35













0












0








0








I'm using Laravel 5.7 along with Passport to create an API for a first-party client. I have a login form that accepts the user's email and password and sends both to a custom LoginController. The LoginController then creates an oAuth payload, sends a POST request to oauth/token via Guzzle and returns the access_token, refresh_token and everything else to my first-party client.



Everything works perfectly when I test it in the browser. However I would now like to write an integration test for all of this and am running into an issue. The issue being that the oAuth server keeps rejecting my client and/or Guzzle request, only during testing.



Here is my corresponding code:



LoginController



<?php

namespace AppHttpControllersApi;

use AppDomainAuthPasswordGrant;
use AppHttpRequestsLoginRequest;

class LoginController extends ApiController

/**
* LoginController constructor.
*/
public function __construct()

$this->middleware('api')->only('login');


/**
* Attempt to authenticate the user with the credentials they provided
* and if successful, return an access token for the user.
*
* @param LoginRequest $request
* @return IlluminateHttpResponse
*/
public function login(LoginRequest $request)

return PasswordGrant::attempt($request->email, $request->password);




PasswordGrant



<?php

namespace AppDomainAuth;

use GuzzleHttpClient as GuzzleHttp;
use GuzzleHttpExceptionClientException;
use LaravelPassportClient;

class PasswordGrant

/**
* The GuzzleHttp client instance.
*
* @var GuzzleHttp
*/
protected $http;

/**
* PasswordGrant constructor.
*
* @param GuzzleHttp $http
*/
public function __construct(GuzzleHttp $http)

$this->http = $http;


/**
* @param $username
* @param $password
* @return IlluminateHttpResponse
*/
public static function attempt($username, $password)

$passwordGrant = resolve(static::class);

$payload = $passwordGrant->oAuthPayload(
$passwordGrant->oAuthClient(), $username, $password
);

return $passwordGrant->oAuthResponse($payload);


/**
* Get the oAuth Client we are using to authenticate our login and user.
*
* @return Client
*/
protected function oAuthClient()

return Client::query()
->where('name', config('api.password_client'))
->where('password_client', true)
->where('revoked', false)
->firstOrFail();


/**
* The payload we need to send to our oAuth server in order to receive
* a bearer token and authenticate the user.
*
* @param Client $client
* @param $username
* @param $password
* @return array
*/
protected function oAuthPayload(Client $client, $username, $password)

return [
'form_params' => [
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $username,
'password' => $password,
'scope' => '*'
]
];


/**
* Get the response from our oAuth server.
*
* @param array $payload
* @return IlluminateHttpResponse
*/
protected function oAuthResponse(array $payload)

try

return $this->http->post(route('passport.token'), $payload)->getBody();

catch (ClientException $exception)

return response($exception->getMessage(), $exception->getCode());






PasswordGrantTest



<?php

namespace TestsFeatureRequestsTeam;

use AppDomainAuthPasswordGrant;
use AppModelsUser;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateSupportFacadesArtisan;
use TestsTestCasesTestCase;

class PasswordGrantTest extends TestCase

use RefreshDatabase;

/** @test */
public function it_returns_an_access_token_for_a_user_with_valid_credentials()

Artisan::call('passport:client', [
'--password' => true,
'--name' => config('api.password_client')
]);

$user = create(User::class);

$result = PasswordGrant::attempt($user->email, 'secret');

dd($result);




The dd at the end of my test always returns a 401 with the message:
"error":"invalid_client","message":"Client authentication failed"



I have triple checked the existence and validity of my user model, the passport client and made sure the payload is well-formed.



Why does the password grant work when I test it via the browser but it does not work when making the same request to the server from my tests?



Perhaps I am missing certain headers in my request to the server during testing?










share|improve this question














I'm using Laravel 5.7 along with Passport to create an API for a first-party client. I have a login form that accepts the user's email and password and sends both to a custom LoginController. The LoginController then creates an oAuth payload, sends a POST request to oauth/token via Guzzle and returns the access_token, refresh_token and everything else to my first-party client.



Everything works perfectly when I test it in the browser. However I would now like to write an integration test for all of this and am running into an issue. The issue being that the oAuth server keeps rejecting my client and/or Guzzle request, only during testing.



Here is my corresponding code:



LoginController



<?php

namespace AppHttpControllersApi;

use AppDomainAuthPasswordGrant;
use AppHttpRequestsLoginRequest;

class LoginController extends ApiController

/**
* LoginController constructor.
*/
public function __construct()

$this->middleware('api')->only('login');


/**
* Attempt to authenticate the user with the credentials they provided
* and if successful, return an access token for the user.
*
* @param LoginRequest $request
* @return IlluminateHttpResponse
*/
public function login(LoginRequest $request)

return PasswordGrant::attempt($request->email, $request->password);




PasswordGrant



<?php

namespace AppDomainAuth;

use GuzzleHttpClient as GuzzleHttp;
use GuzzleHttpExceptionClientException;
use LaravelPassportClient;

class PasswordGrant

/**
* The GuzzleHttp client instance.
*
* @var GuzzleHttp
*/
protected $http;

/**
* PasswordGrant constructor.
*
* @param GuzzleHttp $http
*/
public function __construct(GuzzleHttp $http)

$this->http = $http;


/**
* @param $username
* @param $password
* @return IlluminateHttpResponse
*/
public static function attempt($username, $password)

$passwordGrant = resolve(static::class);

$payload = $passwordGrant->oAuthPayload(
$passwordGrant->oAuthClient(), $username, $password
);

return $passwordGrant->oAuthResponse($payload);


/**
* Get the oAuth Client we are using to authenticate our login and user.
*
* @return Client
*/
protected function oAuthClient()

return Client::query()
->where('name', config('api.password_client'))
->where('password_client', true)
->where('revoked', false)
->firstOrFail();


/**
* The payload we need to send to our oAuth server in order to receive
* a bearer token and authenticate the user.
*
* @param Client $client
* @param $username
* @param $password
* @return array
*/
protected function oAuthPayload(Client $client, $username, $password)

return [
'form_params' => [
'grant_type' => 'password',
'client_id' => $client->id,
'client_secret' => $client->secret,
'username' => $username,
'password' => $password,
'scope' => '*'
]
];


/**
* Get the response from our oAuth server.
*
* @param array $payload
* @return IlluminateHttpResponse
*/
protected function oAuthResponse(array $payload)

try

return $this->http->post(route('passport.token'), $payload)->getBody();

catch (ClientException $exception)

return response($exception->getMessage(), $exception->getCode());






PasswordGrantTest



<?php

namespace TestsFeatureRequestsTeam;

use AppDomainAuthPasswordGrant;
use AppModelsUser;
use IlluminateFoundationTestingRefreshDatabase;
use IlluminateSupportFacadesArtisan;
use TestsTestCasesTestCase;

class PasswordGrantTest extends TestCase

use RefreshDatabase;

/** @test */
public function it_returns_an_access_token_for_a_user_with_valid_credentials()

Artisan::call('passport:client', [
'--password' => true,
'--name' => config('api.password_client')
]);

$user = create(User::class);

$result = PasswordGrant::attempt($user->email, 'secret');

dd($result);




The dd at the end of my test always returns a 401 with the message:
"error":"invalid_client","message":"Client authentication failed"



I have triple checked the existence and validity of my user model, the passport client and made sure the payload is well-formed.



Why does the password grant work when I test it via the browser but it does not work when making the same request to the server from my tests?



Perhaps I am missing certain headers in my request to the server during testing?







php laravel unit-testing oauth-2.0 phpunit






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 0:12









Denis PriebeDenis Priebe

1,36510 silver badges30 bronze badges




1,36510 silver badges30 bronze badges















  • The client_id field is supposed to contain an integer, however I am not sure if your function oAuthClient() returns an integer. Mostly eloquent functions return strings / collections. So check if the value passed to client_id is of type integer / i.e., without quotes.

    – Hari Harker
    Apr 6 at 20:35

















  • The client_id field is supposed to contain an integer, however I am not sure if your function oAuthClient() returns an integer. Mostly eloquent functions return strings / collections. So check if the value passed to client_id is of type integer / i.e., without quotes.

    – Hari Harker
    Apr 6 at 20:35
















The client_id field is supposed to contain an integer, however I am not sure if your function oAuthClient() returns an integer. Mostly eloquent functions return strings / collections. So check if the value passed to client_id is of type integer / i.e., without quotes.

– Hari Harker
Apr 6 at 20:35





The client_id field is supposed to contain an integer, however I am not sure if your function oAuthClient() returns an integer. Mostly eloquent functions return strings / collections. So check if the value passed to client_id is of type integer / i.e., without quotes.

– Hari Harker
Apr 6 at 20:35












0






active

oldest

votes










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55388342%2flaravel-passport-testing-password-grant%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes




Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.







Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55388342%2flaravel-passport-testing-password-grant%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현