Nuxt websockets Laravel Echo 私人频道身份验证未触发

时间:2021-03-02 17:25:33

标签: websocket jwt nuxt.js laravel-echo pusher-js

我目前正在我的 Nuxt 应用程序中实现 websockets。我有一个 Laravel 后端,我使用 Pusher 和 Laravel Echo。问题是,当尝试连接/订阅私人频道时 - 由于客户端是通过广播/身份验证端点授权的,因此不会命中单个频道身份验证 (channels.php)。因此,登录用户有可能访问他们不应该访问的私人频道。

我的代码/配置如下:

NUXT 前端:

nuxt.config.js

echo: {
 broadcaster: 'pusher',
 key: process.env.MIX_PUSHER_APP_KEY,
 cluster: process.env.MIX_PUSHER_APP_CLUSTER,
 forceTLS: process.env.NODE_ENV === 'production',
 authModule: true,
 authEndpoint: `${process.env.API_URL}/broadcasting/auth`,
 connectOnLogin: true,
 disconnectOnLogout: true,
 auth: {
  headers: {
    'X-AUTH-TOKEN': process.env.API_AUTH_TOKEN
  }
 }

},

LARAVEL 后端:

BroadcastServiceProvider.php

public function boot()
{
    Broadcast::routes(['middleware' => [JWTAuthMiddleware::class]]);

    require base_path('routes/channels.php');
}

AuthController.php

public function auth(Request $request): JsonResponse
{
    $pusher = new Pusher(
        config('broadcasting.connections.pusher.key'),
        config('broadcasting.connections.pusher.secret'),
        config('broadcasting.connections.pusher.app_id')
    );
    $auth = $pusher->socket_auth($request->input('channel_name'), $request->input('socket_id'));
    return ResponseHandler::json(json_decode($auth));
}

ChatMessageEvent.php

/**
 * @inheritDoc
 */
public function broadcastOn()
{
    return new PrivateChannel('chat.' . $this->chatMessage->getChatId());
}

channels.php

Broadcast::channel(
'chat.{chatId}',
function (JwtUserDTO $user, int $chatId) {
    Log::info('test');
    return false;
}

);

您可能已经注意到,我们使用存储在客户端的 JWT 身份验证策略 - 因此我们没有会话。但是当通过 auth 端点的授权起作用时,应该可以通过 channels.php 路由来保护各个私有渠道吗?但是正如我在日志中看到的那样,它从未达到过。我错过了一些配置吗?或者为什么我只在 auth 端点上获得授权,而不在各个渠道路由上获得授权?

1 个答案:

答案 0 :(得分:0)

经过大量搜索后,我发现问题出在我的 AuthController.php 上,因为我已经实现了自己的身份验证功能 - 这使得它可以对私人频道的用户进行身份验证。不幸的是,这导致没有解除 BroadcastServiceProvider。所以解决方案是:

use Illuminate\Broadcasting\BroadcastController;

Route::post('broadcasting/auth', [BroadcastController::class, 'authenticate'])
        ->middleware(BroadcastMiddleware::class);

这将使用 Broadcast Facade 并启用 channels.php 以针对给定频道对用户进行身份验证。

我还必须添加一个中间件来在 Laravel 会话中设置经过身份验证的用户,因为这是服务提供者所需要的。

/**
 * @param Request $request
 * @param Closure $next
 * @return mixed
 */
public function handle(Request $request, Closure $next)
{
    /** @var JwtUserDTO $jwt */
    $jwt = $request->get('jwt');
    // Set the user in the request to enable the auth()->user()
    $request->merge(['user' => $jwt]);
    $request->setUserResolver(function() use ($jwt) {
        return $jwt;
    });
    Auth::login($jwt);

    return $next($request);
}

为了做到这一点,我的模型或 DTO 必须实现 Illuminate\Contracts\Auth\Authenticatable 接口。请记住为 getAuthIdentifierNamegetAuthIdentifier 添加功能以分别返回用户名和用户 ID,因为如果您想使用在线状态频道,这也是必需的。