gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:08:49 26 4
gpt4 key购买 nike

我在从 Illuminate 请求 ($request->user()) 获取用户时遇到问题。

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

PusherBroadcastDriver 使用这个,由于显而易见的原因我无法编辑第三方代码..

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

身份验证服务提供商:

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

}

但不幸的是上面的方法不起作用。有人能指出我正确的方向吗?

最佳答案

这是最终的解决方案:

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

关于php - Laravel 5.5 中 $request->user() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46432616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com