Laravel sanctum SPA authentication logout is not working
Asked Answered
W

4

7

I am using laravel sanctum SPA authentication in my Vue project.Everything is working well but even after logout

Auth::logout()

I am still able to get datas from api route inside middleware

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

I should not be able to get datas after logout.It should show 401 unauthenticated but its not the case. How to solve this problem.I have been stuck here for 3 days.I followed laravel documentation and other tutorial as well but every one logged out same like I did.

Wages answered 5/8, 2020 at 11:45 Comment(6)
is sanctum the default guard?Richy
Above route is written in api.php so default guard is api @RichyWages
the default guard is set in the configuration auth.php ... when using the auth functions if you don't pass a guard in it will use the default ... if the default isn't sanctum then you are potentially calling logout on a different guardRichy
Ok then you mean i should pass sanctum guard in logout?Wages
Did you solved your problem? I have the same issue, everything works well with postman, but vue keeps me logged even if I revoke the token through postmanLeavy
Auth::logout() works fine with spaGothart
P
14

Kindly use Auth::guard('web')->logout(); instead of Auth::logout(). look into SPA Log out issue

Preferential answered 17/8, 2020 at 10:43 Comment(0)
P
0

To Logout, a user simply do this in you logout function to delete all the user tokens

public function logout(Request $request) {
auth()->user()->tokens()->delete();
}

Or user this to remove only the active token

$request->user()->currentAccessToken()->delete();
Pipestone answered 22/1, 2022 at 6:41 Comment(0)
R
0

What worked for me now is : auth('sanctum')->user()->tokens()->delete();

Recalesce answered 11/12, 2022 at 8:28 Comment(0)
M
-1

In order to logout the specific user, You need to specify the user.

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

// Get user who requested the logout
$user = request()->user(); //or Auth::user()
// Revoke current user token
$user->tokens()->where('id', $user->currentAccessToken()->id)->delete()
Mesothelium answered 5/8, 2020 at 12:12 Comment(2)
Cleaner way $request->user()->currentAccessToken()->delete();Terrell
I am using SPA authentication not API token authentication.This answer may suit for that.anyway thanks for response.Wages

© 2022 - 2024 — McMap. All rights reserved.