How to logout a user from API using laravel Passport

laravel 5.7 passport logout
laravel passport revoke token
laravel api authentication without passport
laravel passport multiple users
laravel logout
laravel passport custom user table
laravel passport check if user is logged in
laravel passport vs jwt

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.

You need to delete the token from the database table oauth_access_tokens you can do that by creating a new model like OauthAccessToken

  1. Run the command php artisan make:model OauthAccessToken to create the model.

  2. Then create a relation between the User model and the new created OauthAccessToken Model , in User.php add :

    public function AauthAcessToken(){
        return $this->hasMany('\App\OauthAccessToken');
    }
    
  3. in UserController.php , create a new function for logout:

    public function logoutApi()
    { 
        if (Auth::check()) {
           Auth::user()->AauthAcessToken()->delete();
        }
    }
    
  4. In api.php router , create new route :

     Route::post('logout','UserController@logoutApi');
    
  5. Now you can logout by calling posting to URL /api/logout

Something like this maybe will work too if you adapt to your code. $token= $​request->user()->tokens->find($token); $token->revoke();. The user supplies the username of an account and a password if the account has one (in a secure system, all accounts must either have passwords or be invalidated). If the password is correct, the user is logged in to that account; the user acquires the access rights and privileges of the account.

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.

Guys, I'm using Laravel passport for authenticating APIs for mobile app is hasmany //relationship written in User.php to oauth_access_tokens  Also, I'm using \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class in web(as I understand in allows me not to send bearer token in every request). Also, even if I delete everything from oauth_access_tokens table and refresh page or send api request to api:auth protected route I will get info like logged user.

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);
    }

Create an account; Log in; Sign out. Let's go! Create your new controller: php artisan make:controller Api/AuthController. In  Laravel passport - Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use. Access token - A token used to access protected resources.

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'
    ]);
}

How to logout a user from API using laravel Passport 1 front end (with laravel backend to communicate with API) and another laravel project  What is Laravel Passport ? APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel Passport application in a matter of minutes.

Using Ember frontend and Laravel for backend, authentication has also experienced issue with setting to null $request->user using Passport. Next, we need to install a passport using the command, Using passport:install command, it will create token keys for security. So let’s run below command: php artisan passport:install

I am using Laravel with vuejs and passport for authentication. So i have a route group in my api.php file like: Route::group(['middleware' => 'auth:api'], What should I do in order to logout user after session has expired so the  Using Ember frontend and Laravel for backend, authentication has been an easy process with Passport, however, the product lead and designer on my team do not like that you are automatically logged in each time for the two hours the 'laravel_session' is not expired.

Laravel makes API authentication a breeze using Laravel Passport, API endpoint Logout for logging in and out users in a Laravel application. Passport ships with a JSON API that you may use to allow your users to create clients and personal access tokens. However, it can be time consuming to code a frontend to interact with these APIs. So, Passport also includes pre-built Vue components you may use as an example implementation or starting point for your own implementation.

Comments
  • can you see any token in http headers after logout ?
  • What to do about the refresh token?
  • this will delete all entries from AauthAcessToken table against user. What if we want to log out from a specific device only -to delete single entry against user)
  • Since I am new to this, how does laravel creates relationship with the oauth_access_tokens table since it doesn't have any common field with users table
  • this will logout the user from all devices.
  • i am using passport 7.4 and auth()->user()->token()->revoke(); just works fine
  • after this code you can return auth()->user() and its okey?
  • works like charm. This is what i was looking for