2016-04-13 29 views
5

我有認證使用tymon/jwt-auth封裝的JWT用戶中間件:在Controller的構造函數之前在Laravel 5.1上運行中間件?

public function handle($request, \Closure $next) 
{ 
    if (! $token = $this->auth->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); 
} 

然後,我有一個控制器,我想從中間件向控制器傳遞用戶。

所以,我做的控制器上:

public function __construct() 
{ 
    $this->user = \Auth::user(); 
} 

的問題是,$this->usernull,但我這樣做對控制器的方法時,它不是空。

所以:

public function __construct() 
{ 
    $this->user = \Auth::user(); 
} 

public function index() 
{ 
    var_dump($this->user); // null 
    var_dump(\Auth::user()); // OK, not null 
} 

所以,問題是__construct是中間件之前運行。我該如何改變這種情況,還是有另一種解決方案?

更新:我使用dingo/api進行路由,也許這是他們的錯誤?

+0

你不能做到這一點。您已經考慮如何從中間件(而不是控制器)傳遞該用戶。 – num8er

+0

@ num8er即使當我傳遞'$ user'參數時:'$ request-> attributes-> add(compact('user'));'我在控制器上得到相同的結果,因爲構造函數在中間件。 (可能是dingo/api錯誤) – HtmHell

+0

檢查我的回答 – num8er

回答

0

1)從內核的$middleware陣列

2)你的中間件把你的中間件$routeMiddleware數組定義名稱jwt.auth

protected $routeMiddleware = [ 
    // ... 
    'jwt.auth' => 'App\Http\Middleware\YourAuthMiddleware' 
]; 

2)針控制器的父目錄中創建BaseController,與功能:

public function __construct() { 
    $this->middleware('jwt.auth'); 
} 

3)將針控制器從BaseController擴展到

4)使針控制器__construct功能看起來像這樣:

public function __construct() { 
    parent::__construct(); 
    $this->user = \Auth::user(); 
} 
相關問題