【问题标题】:How can I delete the token when the user log out?用户注销时如何删除令牌?
【发布时间】:2021-03-07 10:23:53
【问题描述】:

我制作了一个 UserController,当用户在页面上成功注册时,它会生成一个 accessToken

class UserController extends Controller
{

    /**
     * Login Method: in here we call Auth::attempt with the credentials the user supplied. 
     * If authentication is successful, we create access tokens and return them to the user. 
     * This access token is what the user would always send along with all API calls to have access to the APIs.
     * Register Method: like the login method, we validated the user information, 
     * created an account for the user and generated an access token for the user.
     */
    
    public function login()
        {
            $credentials = [
                'email' => request('email'), 
                'password' => request('password')
            ];

            if (Auth::attempt($credentials)) {
                $success['token'] = Auth::user()->createToken('MyApp')->accessToken;

                return response()->json(['success' => $success]);
            }

            $status = 401;
            $response = ['error' => 'Unauthorized'];

            return response()->json($response, $status);
        }

        public function register(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'email' => 'required|email',
                'password' => 'required',
            ]);

            if ($validator->fails()) {
                return response()->json(['error' => $validator->errors()], 401);
            }

            $input = $request->all();
            $input['password'] = bcrypt($input['password']);

            $user = User::create($input);
            $success['token'] = $user->createToken('MyApp')->accessToken;
            $success['name'] = $user->name;

            return response()->json(['success' => $success]);
        }

        public function getDetails()
        {
            return response()->json(['success' => Auth::user()]);
        }
}

我的问题是我想在用户注销时删除令牌,但我不知道如何从用户那里删除访问令牌。

我的 UserController 中的

logout 功能

 public function logout() 
        {
            Auth::user()->tokens->each(function($token, $key) {
                $token->delete();
            });
        
            return response()->json([
                'message' => 'Logged out successfully!',
                'status_code' => 200
            ], 200);
        }

当我通过 GET 路由使用 postman 对其进行测试时:http://127.0.0.1:8000/api/logout。我错过了什么吗?


更新

这是我的 api.php 文件:

Route::resource('categories', 'App\Http\Controllers\CategoryController');

Route::post('register', 'App\Http\Controllers\UserController@register');
Route::post('login', 'App\Http\Controllers\UserController@login');


/**
 * We can group the routes we need auth for
 * under common middleware. It secures our routes
 */
Route::group(['middleware' => 'auth:api'], function(){

 Route::get('logout', 'App\Http\Controllers\UserController@logout');
});

我正在邮递员中使用以下路由对其进行测试:http://127.0.0.1:8000/api/logout 并将我从登录请求中获得的 Bearer 令牌作为值传递。

【问题讨论】:

    标签: laravel vue.js


    【解决方案1】:

    在您的注销功能中,它应该使令牌过期,而不是删除它

    
        public function logout(Request $request) 
        {
            $request->user()->token()->revoke();
            return response()->json([], Response::HTTP_NO_CONTENT);
        }
    

    或者,如果你想让他的所有令牌过期:

    use Illuminate\Support\Facades\Auth;
    
    public function logout(Request $request)
    {
          $userTokens = Auth::user()->tokens();
          foreach($userTokens as $token) 
          {
               $token->revoke();   
          }
    }
    

    【讨论】:

    • 我都试过了。 错误:在 null 上调用成员函数 token()
    • @Preefix,请检查第二个函数,我编辑了它
    • 你是否已经在邮递员中为请求设置了不记名令牌?身份验证中间件是否应用于注销路由?
    • 不要撤销令牌,因为每次用户登录时都会创建一个新令牌,而当用户注销时,创建的令牌将设置为 Revoked(1)。它不会删除数据库中的令牌。现在想象一下桌子会有多大。
    【解决方案2】:

    它应该是 POST 请求而不是 GET 请求,因为您要删除/更改数据库。

    路线应该是这样的:

    Route::POST('logout', 'App\Http\Controllers\UserController@logout')->middleware('auth:api');
    

    UserController中的注销方法应该是。

    public function logout()
     {
         auth()->user()->tokens->each(function ($token, $key) {
             $token->delete();
         });
         return response()->json([
                'message' => 'Logged out successfully!',
                'status_code' => 200
            ], 200);
     }
    

    【讨论】:

    • 错误:在 null 或 nil 对象标记上调用成员函数 token()。不适合我
    • 这可能是因为您的注销请求不包含令牌。发送注销请求时,请确保您传递了令牌。
    • 我使用授权密钥和承载令牌作为值在邮递员中传递它。
    • 试试这个方法。在 Authorization->Type-> 下选择 Bear Token 并在 Token 字段中仅通过 access_token
    • 还要确保注销路由受到 auth 中间件的保护。因为用户必须先登录才能退出。我在我的回答中更新了注销路线。
    猜你喜欢
    • 2016-11-15
    • 2014-11-20
    • 1970-01-01
    • 2023-03-31
    • 2016-10-11
    • 1970-01-01
    • 2014-04-28
    • 2016-08-06
    • 2022-10-13
    相关资源
    最近更新 更多