Laravel5.5+dingo+swooletw+passport websocket 获取不到 token 对应的用户
RT,目前我用了以上的几个包。我需要websocket连接的时候,将passport分配的access_token通过地址栏传到后端。获取用户的基本信息(ID,用户名,头像等)。
首先因为passport认证的用户,需要通过请求头的Authorization
来获取。我在此处对请求做了一些处理,将地址栏的access_token
转为Authorization
。
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class WebSocketAuthRewirte
{
/**
* Handle an incoming request.
* 处理URL传参过来的access_token.
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($request->has('access_token')) {
$access_token = $request->input('access_token');
$request->headers->add(['Authorization' => $access_token]);
}
return $next($request);
}
}
然后,我在swooletw
的websocket
中间件中,首先通过了这个处理请求头的中间件WebSocketAuthRewirte
。最后在另一个中间件WebSocketAuthorization
中获取当前请求的用户信息,总是获取不到。swooletw
默认的中间件总是为null
,下面这个是我自己写的中间件:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\AuthManager;
use Illuminate\Auth\AuthenticationException;
/**
* Class Authenticate
*/
class WebSocketAuthorization
{
protected $auth;
protected $guard = 'api';
public function __construct(AuthManager $auth)
{
$this->auth = $auth->guard($this->guard);
var_dump($this->auth->user());
//此处打印总是提示错误
// local.ERROR: Auth guard driver [api] is not defined. {"exception":"[object] (InvalidArgumentException(code: 0): Auth guard driver [api] is not defined. at /Users/noecs/Desktop/noecs-laravel-shop/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php:97)
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*
*/
public function handle($request, Closure $next)
{
try {
if ($user = $this->auth->user()) {
$request->setUserResolver(function () use ($user) {
return $user;
});
}
} catch (AuthenticationException $e) {
}
return $next($request);
}
}
求大佬们看看这是什么问题。
推荐文章: