How to logout a user from API using laravel Passport

后端 未结 8 887
夕颜
夕颜 2020-12-12 16:38

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 auth

8条回答
  •  执念已碎
    2020-12-12 16:56

    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.

提交回复
热议问题