2017-09-02 94 views
1

我已經爲JWT認證設置了Tymon包。如果有新用戶註冊或登錄,我會成功獲取令牌。但是當我將令牌傳遞給Laravel JWT時,我發現用戶未找到錯誤。JWT認證user_not_found Tymon

控制器代碼

public function authenticate() 
    { 
     $credentials = request()->only('user_name','password'); 
     try{ 
      $token = JWTAuth::attempt($credentials); 
      if(!$token){ 
       return response()->json(['error'=>'invalid_credentials'],401); 
      } 
     } 
     catch(JWTException $e){ 
      return response()->json(['error'=>'something went wrong'],500); 
     } 
     return response()->json(['token'=>$token],200); 
    } 

    public function register() 
    { 
     $user_name = request()->user_name; 
     $c_name = request()->company_name; 
     $accessibility_level = request()->accessability_level; 
     $password = request()->password; 
     $contact_number = request()->contact_number; 
     $address = request()->address; 

     $user = User::create([ 
      'user_name'=>$user_name, 
      'c_name'=>$c_name, 
      'accessibility_level'=>$accessibility_level, 
      'password'=>bcrypt($password), 
      'contact_number'=>$contact_number, 
      'address'=>$address 
     ]); 

     $token = JWTAuth::fromUser($user); 

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

與上面的代碼沒有問題工作正常。

但是,當我嘗試訪問一些數據與JWT驗證我得到一個錯誤作爲USER_NOT_FOUND。我已經通過郵遞員獲得了作爲標題的令牌。

航線代碼

Route::get('/some_route','[email protected]')->middleware('jwt.auth'); 

而且jwt.php也被設置與我的模型(主鍵)使用了正確的標識

'identifier' => 'user_name', 

回答

2

JWT的標識符不工作通過簡單地修改配置,因爲它是hardcoded作爲代碼中的id由於某種原因

您可以在cal之前使用setIdentifier方法使用任何其他的JWTAuth方法來設置標識符。

方法如下:

public function authenticate() 
    { 
     $credentials = request()->only('user_name','password'); 
     try{ 
      $token = JWTAuth::setIdentifier('user_name')->attempt($credentials); 
      if(!$token){ 
       return response()->json(['error'=>'invalid_credentials'],401); 
      } 
     } 
     catch(JWTException $e){ 
      return response()->json(['error'=>'something went wrong'],500); 
     } 
     return response()->json(['token'=>$token],200); 
    } 

那麼對於智威湯遜認證創建一個自定義的中間件:

public function handle($request, \Closure $next) 
    { 
     if (! $token = $this->auth->setIdentifier('user_name')->setRequest($request)->getToken()) { 
      return $this->respond('tymon.jwt.absent', 'token_not_provided', 400); 
     } 

     try { 
      $user = $this->auth->authenticate($token); 
     } catch (TokenExpiredException $e) { 
      return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]); 
     } catch (JWTException $e) { 
      return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]); 
     } 

     if (! $user) { 
      return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404); 
     } 

     $this->events->fire('tymon.jwt.valid', $user); 

     return $next($request); 
    }