Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

murilo's avatar
Level 10

Pest Test in Laravel with Gand Type Authorization

hello , I am new in testing with Pest . I am trying to loggin with my Gand Type Password Passport Token , in a area that I have that is protected .

well , in my TestCase.php I added the seed = true , so that I could use my Seed and use those users .

<?php

namespace Tests;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;

abstract class TestCase extends BaseTestCase
{
    //use CreatesApplication, RefreshDatabase;
    use CreatesApplication, DatabaseTransactions;
    protected $seed = true;

}

phpunit.xml file , I unchecked all those items , it is like this -

 <env name="APP_ENV" value="testing"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="DB_CONNECTION" value="sqlite"/>
        <env name="DB_DATABASE" value=":memory:"/>
        <env name="MAIL_MAILER" value="array"/>
        <env name="PULSE_ENABLED" value="false"/>
        <env name="QUEUE_CONNECTION" value="sync"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="TELESCOPE_ENABLED" value="false"/>

and finaly on my test method -

test('list-users', function () {

    //$oauth_clients  = \DB::table('oauth_clients')->select('id')->pluck('id')->toArray();
    $user = User::whereHas('AcessAreas',  function ($query)  {
        return $query->where('url_title', 'supervisor');
    })->first();

    $data = [
        'email' => $user->email,
        'password' => '123456',
        'device_name' => 'e2e_test',
    ];

    $token =  postJson(route('postLoginGrandType'),$data)->json(['access_token']);
dd($token);

the result will show the token -

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5YmUzMDA5Yi02NmUyLTQ0MDAtOTdkMi05MjExMmQ3ZGI0Y2IiLCJqdGkiOiIzYzI5YzZhMjAwODRmNzQ0YThkOWYwY2U0NmRjN2FmZTQ5ZDczMmUzMTE4MjQzNjhjYjhhNjZlYTVmNjQ0YTlmNTg0YTdkNGVmYmFhYzAxZSIsImlhdCI6MTcxNDA1NDEwNS44MzU4MjUsIm5iZiI6MTcxNDA1NDEwNS44MzU4MjYsImV4cCI6MTcxNDE0MDUwNS44Mjc4MzYsInN1YiI6IjEiLCJzY29wZXMiOlsiKiJdfQ.DoCTPnUuiEtsf-ihhrkfLCmhiXQd7PLJSgeEmtkPyfwmDFOHdDuSORLeX2gbPyI1FgklI_e8WBwvZwGHhQHi0QoKvixNUXlUG59NX1AAmTp0qcOTtehrYoEvDkgj1B4Sxcr4pcMHsrEDfcknd6vV6j-dV4lOSNoMk7kMMXerE6IaJ2tdkObJ_n-xqHa50MzGzDuuPrCLuj-6wdPbf3DZmvTk_tcNdIxtlbdHxt5iiDKq1GNzIT1K-xrVZl01T_KCkh0wV8L4OoEP5RsMUZ3A5WwUkNM9XVOMqUwBMHIwR4BsSoxMY8A9nz-Vr6gfkaTBxVwcltZL4o-Ef9gijAjhnkw_kCXr3CcKaCj7U6tJO_MS3QMfVC1NWJshTpdwU8qUUK-pfryJpewZCQf214BqfDhTtET-wq5hTE582zqVbRcsoSuoaBY9n6TXDq8QfUVP6CnbPFXstwnbTJKfyZ4nWVk_DafbJyDRb7ReN9siDbQXZP5hiGNXcHagYAh-Y5WvopWqKTR6iETqSJ00P4mktZRgRKQ6hCf0RzZl6L3ZI0r1hKMt045PVeNpNY4kQCOSayge8BGKTyv1qjqkwmMDWL-Tsevr-X5tibzm7k2csemmWdWqbz_HmSSSZchRC_bSKWi3DPd4JpZR6OOPsS5XhRh6kDV03b9vOZ55yJl1-FQ

until now it is ok . Now I want to connect to this route in API -

Route::group(['middleware' => ['auth:api',  'scope:my-scope']] , function () {
    Route::get('/users', [AdminAuthController::class, 'users'])->name('users');

if I go at postman with that token that I created in the test , I am able to connect this router successfully . BUT, if I proceed with the test , like this -

test('list-users', function () {

    //$oauth_clients  = \DB::table('oauth_clients')->select('id')->pluck('id')->toArray();
    $user = User::whereHas('AcessAreas',  function ($query)  {
        return $query->where('url_title', 'supervisor');
    })->first();

    $data = [
        'email' => $user->email,
        'password' => '123456',
        'device_name' => 'e2e_test',
    ];

    $token =  postJson(route('postLoginGrandType'),$data)->json(['access_token']);
  $data = getJson(route('users'), [
        'Authorization' => "Bearer {$token}"
    ])->json();
    dd($data);

the result will be -

array:2 [
  "message" => "Unauthenticated."
  "code" => 401
] // te

I tryed to create as well , the althentication token like this -

https://laravel.com/docs/10.x/passport#testing

 $token =  Passport::actingAs(
        User::factory()->create(),
        ['my-scope']
    );
 
    $response = $getJson(route('users'), [
        'Authorization' => "Bearer {$token}"
    ])->json();
 

but I didnt managed as well, I didnt understand how this - Passport::actingAs methods works

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

It seems like you're facing an issue with authenticating your API routes in your Pest tests using Laravel Passport. The Passport::actingAs() method is intended to simplify testing by allowing you to authenticate a user without actually going through the OAuth process. However, it seems you're trying to use both methods (direct token generation and Passport::actingAs) which might be causing confusion.

Here's a step-by-step solution to ensure your tests are set up correctly for testing authenticated routes using Laravel Passport:

  1. Ensure Passport is Set Up Correctly: Before testing, make sure Laravel Passport is installed and configured correctly in your application.

  2. Use Passport's ActingAs for Testing: Since you're using Laravel Passport, you can utilize the Passport::actingAs() method to authenticate a user for testing purposes. This method bypasses the need to manually create a token and simplifies the process.

  3. Modify Your Test Case: Here's how you can modify your test case to use Passport::actingAs:

test('list-users', function () {
    // Create a user with necessary scopes
    $user = User::factory()->create();
    Passport::actingAs($user, ['my-scope']);

    // Make a request to the protected route
    $response = $this->getJson(route('users'));

    // Assert the response status and structure
    $response->assertOk()
             ->assertJsonStructure([
                 // Specify the expected structure of the JSON response
             ]);
});
  1. Ensure Correct Headers and Configuration:

    • Make sure your API routes are using the auth:api middleware.
    • Ensure your phpunit.xml is configured to use the correct environment settings that match your local or development setup.
  2. Debugging Tips:

    • Check the logs for any underlying errors during the test execution.
    • Ensure that the database is correctly set up for testing, and the user factory creates users that meet the requirements of your authentication process (e.g., correct scopes, valid credentials).
  3. Run the Test:

    • Execute your tests using the Pest PHP command or through your IDE.

By following these steps, you should be able to test your authenticated routes effectively using Laravel Passport with Pest PHP. Remember, the key advantage of using Passport::actingAs() is that it simplifies authentication in tests by not requiring you to manually handle tokens.

Please or to participate in this conversation.