I've created a project using Laravel 11 + Santum and Nuxt 3 as a front end SPA. I am using SPA authentication (not token based).
I've successfully been able to log in, log out and call various endpoints such as api/user but I get this specific issue:
- If I log in as one user and then log out, then try and log in as a different user, I get a 401 unauthorised response when calling api/user but only on the first attempt. If I hit log in again I get a normal 200 response and no issues.
I've found that if I remove the auth:sanctum middleware from my api/logout route, this issue goes away. I am not sure why this happens as I get no errors with or without the middleware on the api/logout route. I am wondering if somehow the laravel_session cookie is somehow re-generated for the first user after my logout controller method completes when using the auth:santum middleware (complete guess).
For reference her is my api.php declaration:
// Route for logging out the user
Route::middleware('auth:sanctum')->post('/logout', [AuthController::class, 'logout']);
And here is my controller method for logging out the user:
public function logout(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate(); // Invalidate the session
$request->session()->regenerateToken(); // Regenerate the CSRF token
// Create cookies to be cleared
$forgetLaravelSession = Cookie::forget('laravel_session', '/', '.localhost');
$forgetXSRFToken = Cookie::forget('XSRF-TOKEN', '/', '.localhost');
Log::info('User logged out');
return response()->json(['message' => 'Logged out successfully'], 200)
->withCookie($forgetLaravelSession)
->withCookie($forgetXSRFToken);
}
You can see there is some logic to clear cookies on the front end which I added whilst trying to resolve the problem but trying to force forget the cookies does not actually work (not for the laravel_session cookie anyway).
As above, my current solution is remove the auth:sanctum middleware from the api/logout route and I no longer get the issue. My only thought is that surely the api/logout route should have the auth:sanctum middleware on it as I would expect only an authorised user to be calling this?
Any ideas as to why this may be happening and what I can do to get this working whilst keeping the auth:sanctum middleware on the api/logout route?
Many thanks,
Stephen.