首页 > 解决方案 > 用户注销时如何删除令牌?

问题描述

我制作了一个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中的注销功能

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

当我使用邮递员使用GET路由对其进行测试时: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 令牌作为值传递。

标签: laravelvue.js

解决方案


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


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

推荐阅读