How to logout a user from API using laravel Passport

后端 未结 8 891
夕颜
夕颜 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 17:08

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

    This is my first post.. and i find a clean solution (Laravel last Version)

    /**
     * Logout api
     *
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {        
        if (Auth::check()) {
            $token = Auth::user()->token();
            $token->revoke();
            return $this->sendResponse(null, 'User is logout');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised'] , Response::HTTP_UNAUTHORIZED);
        } 
    }
    
    0 讨论(0)
提交回复
热议问题