Running middleware before controller constructor on Laravel 5.1?

I have middleware that authenticates a JWT user with tymon / jwt-auth package:

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); } 

Then I have a controller, and I want to transfer the user from middleware to the controller.

So, I did on the controller:

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

The problem is that $this->user is null , but when I do it using the controller method, it is not zero.

So:

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

So the problem is that __construct is executed before the middleware. How can I change this, or do you have another solution?

Update: I use dingo / api for routing, maybe this is an error on their side?

+5
source share
1 answer

1) Remove your middleware from the core of $middleware array

2) Put your middleware in the $routeMiddleware with the custom name jwt.auth :

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

2) Create a BaseController in the parent directory of the needle controller with the function:

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

3) Extend the needle controller from BaseController

4) Make the needle controller __construct function as follows:

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

Source: https://habr.com/ru/post/1247068/


All Articles