How to logout a user from API using laravel Passport

Joren vh picture Joren vh · Apr 10, 2017 · Viewed 53.5k times · Source

I'm currently using 2 projects. 1 front end (with laravel backend to communicate with API) and another laravel project (the API).

Now I use Laravel Passport to authenticate users and to make sure every API call is an authorized call.

Now when I want to log out my user, I send a post request to my API (with Bearer token) and try to log him out of the API (and clear session, cookies,...)

Then on the client I also refresh my session so the token is no longer known. Now when I go back to the login page, it automatically logs in my user. (Or my user is just still logged in).

Can someone explain me how to properly log out a user with Laravel passport?

Thanks in advance.

Answer

Koushik Das picture Koushik Das · Oct 12, 2018

Make sure that in User model, you have this imported

use Laravel\Passport\HasApiTokens;

and you're using the trait HasApiTokens using

use HasApiTokens

inside the user class. Now you create the log out route and in the controller, do this

$user = Auth::user()->token();
$user->revoke();
return 'logged out'; // modify as per your need

This will log the user out from the current device where he requested to log out. If you want to log out from all the devices where he's logged in. Then do this instead

DB::table('oauth_access_tokens')
        ->where('user_id', Auth::user()->id)
        ->update([
            'revoked' => true
        ]);

This will log the user out from everywhere. This really comes into help when the user changes his password using reset password or forget password option and you have to log the user out from everywhere.