jose.ares's avatar

Laravel Sanctum feature test logout HTTP incorrect response

Hi all, I'm having issues when implementing feature tests for logging out Laravel Sanctum. I have the middleware applied to some route like so:

Route::group(['middleware' => ['auth:sanctum', 'user.active']], function () {
			Route::get('/profile', 'Auth\Controllers\ProfileController@show')->name('profile.show');
});

Login is working fine, returning a JSON response with a proper Sanctum created token.

Logout is:

public function __invoke()
    {
        auth()->user()->currentAccessToken()->delete();

        return $this->jsonResponse()->setMessage('Successfully logged out.');
    }

Now, the test is:

protected $route = 'auth.logout';

public function test_user_can_logout_successfully()
{
        $this->http()->assertUnauthorized();

        $user = create(User::class);

        Sanctum::actingAs(
            $user ,
            ['*']
        );

       // I login
        $this->httpPost('auth.login', [
            'email' => $user->email,
            'password' => env('TESTING_DEFAULT_PASS')
        ]);

       // This goes well, I can see the profile route as I'm logged in
        $this->httpGet('profile.show')->assertOk();

       // I logout, then I destroy the token
        $this->httpPost('auth.logout')->assertOk();

        // Then I try again to see the profile and this time I should get a 401
        $this->httpGet('profile.show')->assertUnauthorized();
}

Thing is I always receive a HTTP 200 code instead of 401. But when I try manually via Postman, it works fine.

Am I missing something regarding test configuration? If I should post more info for this issue, please do let me know

Kind regards

0 likes
1 reply
bugsysha's avatar

Hard to tell based on your project-specific methods like httpPost and so on. Have you tried other methods of revoking tokens?

// Revoke all tokens...
$user->tokens()->delete();

// Revoke the token that was used to authenticate the current request...
$request->user()->currentAccessToken()->delete();

// Revoke a specific token...
$user->tokens()->where('id', $tokenId)->delete();

Also, what is your auth configuration? Maybe you need to pass guard to the auth() function?

Please or to participate in this conversation.