在JWT中注销不起作用

时间:2018-08-11 07:13:03

标签: php laravel authentication jwt

我是Laravel的新手,我安装了JWT并登录,因此它可以工作并生成令牌,当我在邮递员中注销时,它返回true,但一次又一次返回true,并且

  

auth()-> user()

总是在注销后返回用户

这是我的代码:

  public function login(Request $request)
  {

    $this->validateLogin($request);

    if (!$jwt_token = JWTAuth::attempt($request->toArray())) {
      return response()->json([
        'success' => false,
        'message' => 'Invalid national_id or Password',
      ], 401);
    }

    return response()->json(['success' => true, 'token' => $jwt_token,], 200);

  }

并退出:

  public function logout(Request $request)
  {
    auth()->logout();
    return response()->json(['data' => 'you logged out successfully'],200)
  }

在路线上:

Route::group(['prefix' => 'v1', 'namespace' => 'Api\v1'], function() {

  Route::post('login', 'Auth\LoginController@login');
});

    Route::group(['middleware' => ['auth:api', 'api'], 'prefix' => 'v1', 'namespace' => 'Api\v1'], function() {

    // Authentication Routes...
      Route::post('logout', 'Auth\LoginController@logout')->name('logout');
    .
    .
    .
    .
    .

我也再次使用了JWTAuth::invalidate($request->token);,它不起作用。

3 个答案:

答案 0 :(得分:1)

JWT是无状态的,因此令牌将一直有效直到它到期(您设置了到期时间)。 从前端删除令牌,或在黑名单中始终检查所请求的令牌是validnot black listed

我找到了一种方法in github

public function testUserLogoutBlacklistsToken()
{
    // Arrange
    $user = factory('App\Models\User')->create();
    $token = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($user);
    $payload = \Tymon\JWTAuth\Facades\JWTAuth::getPayload($token);
    $headers = ['AUTHORIZATION' => 'Bearer ' . $token];

    // Assert
    $this->get('api/auth/logout', $headers)
         ->seeStatusCode(202)
         ->seeHeader('Authorization', '');

    // Verify on the back-end that the token is blacklisted
    $this->assertTrue(\Tymon\JWTAuth\Facades\JWTAuth::getBlacklist()->has($payload));
}

public function testAccessDeniedWithBlacklistedToken()
{
    // Arrange
    $user = factory('App\Models\User')->create();
    $token = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($user);
    \Tymon\JWTAuth\Facades\JWTAuth::invalidate($token);

     // Sanity check that JWTAuth::invalidate worked
     $this->assertTrue(\Tymon\JWTAuth\Facades\JWTAuth::getBlacklist()->has($payload));

    // User data should not be returned and response should have HTTP 500
    $this->get('api/me', $headers)
         ->seeStatusCode(500);
}

答案 1 :(得分:1)

我希望这对您有用

y

答案 2 :(得分:0)

尝试执行此操作,而不是不声明auth()的警卫,尝试将其声明为api

在您的logout函数中,看起来像这样。

public function logout() {
        auth( 'api' )->logout();
        $json = [
            'success' => true,
            'code'    => 200,
            'message' => 'You are Logged out.',
        ];

        return response()->json( $json, '200' );
    }

然后重试

api/me