I'm having issues with getting the user from an Illuminate Request ($request->user()).
$request->user() // whatever i do this keeps returning null
The PusherBroadcastDriver uses this and i can't edit third party code for obvious reasons..
I'm using Tymon\JWT to generate tokens and authenticate users with my application. I currently tried to do the following (check code)
AUTHENTICATION SERVICE PROVIDER:
public function boot()
{
$this->registerPolicies();
Auth::extend('jwt', function ($app, $name, array $config) {
return new JWTGuard($app['tymon.jwt'],
Auth::createUserProvider($config['provider']),
$app['request']);
});
}
MIDDLEWARE:
public class JWTRefreshMiddleware extends RefreshToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
*
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = parent::handle($request, $next);
$this->addUserToRequest();
return $response;
}
private function addUserToRequest()
{
$request = app('request');
$user = User::find(JWTAuth::getPayload()['user_id']);
$request->merge(['user' => $user]);
$request->setUserResolver(function () use ($user) {
return $user;
});
Auth::setUser($user);
}
}
But unfortunately the above didn't work. Can someone point me in the right direction?
This is the final solution:
class JWTRefreshMiddleware extends RefreshToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
*
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = parent::handle($this->addUserToRequest($request), $next);
return $response;
}
private function addUserToRequest(\Illuminate\Http\Request $request): \Illuminate\Http\Request
{
$user = User::find(JWTAuth::manager()->decode(JWTAuth::getToken())['user_id']);
$request->merge(['user' => $user]);
$request->setUserResolver(function () use ($user) {
return $user;
});
Auth::setUser($user);
return $request;
}
}
It seems you are changing a variable, not the request instance, maybe you can try this.
public function handle($request, Closure $next)
{
$response = parent::handle($this->addUserToRequest($request), $next);
return $response;
}
private function addUserToRequest($request)
{
$user = User::find(JWTAuth::getPayload()['user_id']);
$request->merge(['user' => $user]);
$request->setUserResolver(function () use ($user) {
return $user;
});
Auth::setUser($user);
return $request;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With