如何使用 Laravel Passport 从 API 注销用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43318310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:43:11  来源:igfitidea点击:

How to logout a user from API using laravel Passport

laravellaravel-passport

提问by Joren vh

I'm currently using 2 projects. 1 front end (with laravel backend to communicate with API) and another laravel project (the API).

我目前正在使用 2 个项目。1 个前端(使用 Laravel 后端与 API 通信)和另一个 Laravel 项目(API)。

Now I use Laravel Passport to authenticate users and to make sure every API call is an authorized call.

现在我使用 Laravel Passport 来验证用户并确保每个 API 调用都是经过授权的调用。

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,...)

现在,当我想注销我的用户时,我向我的 API(带有 Bearer 令牌)发送一个 post 请求并尝试将他从 API 注销(并清除会话、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?

有人可以解释我如何正确注销使用 Laravel 护照的用户吗?

Thanks in advance.

提前致谢。

采纳答案by Mahdi

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

您需要从数据库表中删除令牌,oauth_access_tokens您可以通过创建一个新模型来做到这一点OauthAccessToken

  1. Run the command php artisan make:model OauthAccessTokento create the model.

  2. Then create a relation between the Usermodel and the new created OauthAccessTokenModel , in User.phpadd :

    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
  1. 运行命令php artisan make:model OauthAccessToken以创建模型。

  2. 然后在User模型和新创建的 OauthAccessTokenModel之间创建关系,User.php添加:

    public function AauthAcessToken(){
        return $this->hasMany('\App\OauthAccessToken');
    }
    
  3. 在 UserController.php 中,创建一个新的注销函数:

    public function logoutApi()
    { 
        if (Auth::check()) {
           Auth::user()->AauthAcessToken()->delete();
        }
    }
    
  4. 在 api.php 路由器中,创建新路由:

     Route::post('logout','UserController@logoutApi');
    
  5. 现在您可以通过调用发布到 URL 来注销 /api/logout

回答by Koushik Das

Make sure that in Usermodel, you have this imported

确保在User模型中,您已导入

use Laravel\Passport\HasApiTokens;

and you're using the trait HasApiTokensusing

并且您正在使用特征HasApiTokens使用

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.

这将从任何地方注销用户。当用户使用重置密码或忘记密码选项更改密码并且您必须从任何地方注销用户时,这真的很有帮助。

回答by PHP Worm...

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)

在 userController 中创建一个注销功能(或在您的路线中提到)

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

回答by Ramadhan

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

回答by Ankit Sardhara

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

我正在使用 Laravel 6.12.0,以下功能对我有用。

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