How to logout a user from API using laravel Passport
Make sure that in User
model, you have this imported
use Laravel\Passport\HasApiTokens;
and you're using the trait HasApiTokens
in the User
model class 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
$tokens = $user->tokens->pluck('id');
Token::whereIn('id', $tokens)
->update(['revoked', true]);
RefreshToken::whereIn('access_token_id', $tokens)->update(['revoked' => true]);
Make sure to import these two at the top
use Laravel\Passport\RefreshToken;
use Laravel\Passport\Token;
This will revoke all the access and refresh tokens issued to that user. 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.
You need to delete the token from the database table oauth_access_tokens
you can do that by creating a new model like OauthAccessToken
Run the command
php artisan make:model OauthAccessToken
to create the model.-
Then create a relation between the
User
model and the new createdOauthAccessToken
Model , inUser.php
add :public function AauthAcessToken(){ return $this->hasMany('\App\OauthAccessToken'); }
-
in UserController.php , create a new function for logout:
public function logoutApi() { if (Auth::check()) { Auth::user()->AauthAcessToken()->delete(); } }
-
In api.php router , create new route :
Route::post('logout','UserController@logoutApi');
- Now you can logout by calling posting to URL
/api/logout
This is sample code i'm used for log out
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
]);
}
Create a route for logout:
$router->group(['middleware' => 'auth:api'], function () use ($router) {
Route::get('me/logout', 'UserController@logout');
});
Create a logout function in userController ( or as mentioned in your route)
public function logout() {
$accessToken = Auth::user()->token();
DB::table('oauth_refresh_tokens')
->where('access_token_id', $accessToken->id)
->update([
'revoked' => true
]);
$accessToken->revoke();
return response()->json(null, 204);
}