Laravel Sanctum SPA Logout Testing

Viewed 365

I logout of my application via:

Auth::guard('web')->logout();

Please note, it's the SPA use of Sanctum so no tokens.

Then in my test, I check if the user is logged out via:

Sanctum::actingAs(User::first(), ['*']);
$response = $this->postJson(
    route('logout')
); // runs auth logout
$this->assertGuest();

The above fails, yet, when I do not use Sanctum::actingAs(User::first(), ['*']); and instead do a call to my login:

$response = $this->postJson(
            route('login'),
            [
                'email' => User::first()->email,
                'password' => 'xyz',
            ]
        );

The test passes.

Am I missing something with Sanctum::actingAs(User::first(), ['*']);, the docs say to use this for testing, does this not work when it's an SPA with cookie based authentication?

1 Answers

Change your logout middleware to web:

Route::middleware('auth:web')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
});

Then, in logout():

class AuthController extends Controller
{
   /**
   * @return JsonResponse
   */
   public function logout(): JsonResponse
   {
    // If with tokens - delete them:
    // Auth::user()->tokens()->delete();

    Auth::guard('web')->logout();

    return response()->json([
        'message' => 'Tokens Revoked'
    ]);
   }
}
Related