Use Sanctum.
OAuth is not meant to be used to authenticate your own apps.
I had created an API for login using passport. It authenticates using "/oauth/token" URL with password grant type. The API works in the application as well as postman. But while calling the API in tests, it says "Client authentication failed". I've made sure the database migration and passport:install commands are called before calling the API in the test function. But still doesn't work. I tried many solutions like calling a proxy request but the error still remains. Please help. Below is my code for the API:
public function login(LoginRequest $request)
{
if (Auth::attempt($request->validated())) {
$oClient = PassportClient::where('password_client', 1)->first();
return $this->getTokenAndRefreshToken($oClient, request('email'), request('password'));
} else {
return new JsonResponse(
['message' => 'Invalid credentials'],
Response::HTTP_UNAUTHORIZED
);
}
}
public function getTokenAndRefreshToken(PassportClient $oClient, $email, $password)
{
$response = Http::asForm()->post(config('app.url') . '/oauth/token', [
'grant_type' => 'password',
'client_id' => $oClient->id,
'client_secret' => $oClient->secret,
'username' => $email,
'password' => $password,
'scope' => '*',
]);
if ($response->successful()) {
return new LoginResource($response->json());
} else {
return new JsonResponse(
['message' => 'Authentication failed'],
Response::HTTP_UNAUTHORIZED
);
}
}
Below is my test class:
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
// $this->artisan('migrate:fresh');
// $this->artisan('passport:install', ['-vvv' => 1]);
$this->artisan('passport:install');
}
public function test_user_can_login_using_api()
{
$this->withoutExceptionHandling();
$user = \App\Models\User::factory()->create();
$this->postJson(
'/api/auth/login',
[
'email' => $user->email,
'password' => 'password'
],
['Accept' => 'application/json']
)->assertStatus(200);
}
This is my repository where It can be tested.
Please or to participate in this conversation.