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

Narco's avatar
Level 5

Testing a route behind auth:api passport middleware

Hey guys so I'm trying to test a route that is protected by oauth2 (passport package). I'm creating a client and a user and then making a post request to oauth/token with the correct query parameters (grant_type, client_id, client_secret, username, password, scope) but I constantly get a 401 Unauthorized back. If I make the same request through postman I get back the token.

I know the oauth2 is working correctly from my manual tests with postman, but I'm unable to make the tests pass with phpunit.

I also tried running the tests without middleware but then I get a 404 error. I'm using the dingo package for the api.

Any help would be appreciated!

0 likes
3 replies
Narco's avatar
Narco
OP
Best Answer
Level 5

The reason I was getting a 404 when I tried to use the WithoutMiddleware is because the dingo api package uses middleware to capture requests that target the API and handles them appropriately.

So in order to test the auth:api middleware just make sure to send this as the header in your requests:


/**
 * Return request headers needed to interact with the API.
 *
 * @return Array array of headers.
 */
protected function headers($user = null)
{
    $headers = ['Accept' => 'application/json'];

    if (!is_null($user)) {
        $token = $user->createToken('Token Name')->accessToken;
        $headers['Authorization'] = 'Bearer ' . $token;
    }

    return $headers;
}


/** @test */
    public function itTestsSomething()
    {
        $user = factory(User::class)->create();

        $this->post('/url', $data, $this->headers($user));

        // your assertions
    }

Also if you are using database migrations, make sure you initialize a passport client before the test.

2 likes
Bahjaat's avatar

Maybe use this one (like the docs):

Passport::actingAs(
        factory(User::class)->create()
    );
$response = $this->post('/api/create-server');

$response->assertStatus(200);
3 likes

Please or to participate in this conversation.