$ request-> user()在Laravel 5.5中返回null

时间:2017-09-26 17:33:58

标签: php laravel authentication jwt pusher

我遇到了从Illuminate Request($ request-> user())获取用户的问题。

 $request->user() // whatever i do this keeps returning null

PusherBroadcastDriver使用此功能,我出于显而易见的原因无法编辑第三方代码。

我正在使用Tymon \ JWT生成令牌并使用我的应用程序对用户进行身份验证。我目前尝试执行以下操作(检查代码)

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

}

中间件:

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

}

但不幸的是,上述方法无效。 有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:1)

您似乎正在更改变量,而不是请求实例,也许您可​​以尝试此操作。

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

答案 1 :(得分:1)

这是最终解决方案:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div class="app"></div>