2017-09-02 67 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); 
    }