How to logout a user from API using laravel Passport

后端 未结 8 882
夕颜
夕颜 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:51

    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
    0 讨论(0)
  • 2020-12-12 16:51

    Below is the simplest way I found to do it.

    1. USE database SESSION INSTEAD OF file SESSION

    Official documention

    php artisan session:table
    php artisan migrate
    

    Replace SESSION_DRIVER=file by SESSION_DRIVER=database in your .env file.

    2. DELETE USER SESSION RIGHT AFTER LOGIN

    After a user is redirected to your frontend and logs in to finally get a token, you probably call a route in api/routes.php to get the user information, that's where I'm closing the user backend session before sending back user information to the frontend:

    Route::middleware('auth:api')->get('/user', function (Request $request) {
        // Close user session here
        Illuminate\Support\Facades\DB::table('sessions')
            ->whereUserId($request->user()->id)
            ->delete();
        return $request->user();
    });
    

    3. REVOKE TOKENS AT LOGOUT

    Then, to "log out" (actually, revoke tokens) the user from the frontend, you just need to call another route to revoke the token and refresh_token:

    Route::middleware('auth:api')->post('/logout', function (Request $request) {
        // Revoke access token
        // => Set oauth_access_tokens.revoked to TRUE (t)
        $request->user()->token()->revoke();
    
        // Revoke all of the token's refresh tokens
        // => Set oauth_refresh_tokens.revoked to TRUE (t)
        $refreshTokenRepository = app('Laravel\Passport\RefreshTokenRepository');
        $refreshTokenRepository->revokeRefreshTokensByAccessTokenId($request->user()->token()->id);
    
        return;
    });
    

    You may prefer to put these two closures in the UserController.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 17:01

    Hope help someone:

     if (Auth::check()) {
       $request->user()->tokens->each(function ($token, $key) {
            $token->delete();
        });
     }
    

    Good Luck.

    0 讨论(0)
  • 2020-12-12 17:04

    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'
        ]);
    }
    
    0 讨论(0)
  • 2020-12-12 17:06

    I am using Laravel 6.12.0, below function is working for me.

    public function logout(Request $request){
                $accessToken = Auth::user()->token();
                $token= $request->user()->tokens->find($accessToken);
                $token->revoke();
                $response=array();
                $response['status']=1;
                $response['statuscode']=200;
                $response['msg']="Successfully logout";
                return response()->json($response)->header('Content-Type', 'application/json');
            }
    
    0 讨论(0)
提交回复
热议问题