簡體   English   中英

在 Laravel 5.1 上的控制器構造函數之前運行中間件?

[英]Run Middleware Before Controller's Constructor On Laravel 5.1?

我有一個使用tymon/jwt-auth包對 JWT 用戶進行身份驗證的中間件:

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 ,但是當我在控制器的方法上執行此操作時,它不是 null 。

所以:

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進行路由,也許這是他們這邊的錯誤?

您應該在路由中使用中間件

Route::middleware('jwt.auth')->group(function() {
// your routes 
});

1) 從內核的$middleware數組中刪除$middleware

2) 將您的中間件放入帶有自定義名稱jwt.auth $routeMiddleware數組:

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

2)在needle controller的父目錄下創建BaseController,功能:

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

3) 從 BaseController 擴展針控制器

4) 使針控制器的 __construct 函數如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM