using postman:
- I can access the route using a client grant from a token obtained in /oauth/token
- I can also access the route using a token from the login user (personal access client)
however, I'm encountering problems when I'm writing tests when I simulate getting access from oauth/token then logging in to get the access token for the user, and using that user token in this particular route I have no problems (test_get_products_using_authenticated_user)
But when I use the Passport::actingAs I get an error (test_get_products_using_authenticated_user2)
here is the code snippet
public function test_get_products_using_authenticated_user(): void
{
$data = [
'email' => CustomerSeeder::CUSTOMER_EXAMPLE_EMAIL,
'password' => CustomerSeeder::CUSTOMER_EXAMPLE_PASSWORD,
];
$loginResponse = $this->withHeaders([
'Authorization' => 'Bearer ' . $this->generateAccessToken(),
])->postJson('/api/login', $data);
$loginResponse->assertStatus(200);
$loginToken = $loginResponse->json('data.token');
$response = $this->withHeaders([
'Authorization' => 'Bearer ' . $loginToken,
])->getJson('/api/products');
$response = $this->get('/api/products');
$response->assertStatus(200);
}
public function test_products_using_authenticated_user2(): void
{
$user = User::where('email', CustomerSeeder::CUSTOMER_EXAMPLE_EMAIL)->first();
Passport::actingAs(
$user,
[],
'api'
);
$response = $this->get('/api/products');
$response->assertStatus(200);
}
I get for the second test
Route [login] not defined.
at tests\Feature\api\ProductTest.php:58
54▕ 'api'
55▕ );
56▕
57▕ $response = $this->get('/api/products');
➜ 58▕ $response->assertStatus(200);
59▕ }
60▕ }
61▕
product route
Route::group(['prefix' => 'products', 'middleware' => 'client'], function () {
Route::get('/', [ProductController::class, 'index'])- >name('product.list');
});
http/kernel.php
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'client' => CheckClientCredentials::class,
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
when I change my product route from middleware to 'auth:api', tests seem to be fine, but this is not what I want since I also want client to grant access to this route
what am I missing here? I'm using Laravel 10.10, passport 12, and PHP 8.1
login, but you have no routes with that name and that is why you are getting Error in your second test. You should name you login route.