3

我在广播/身份验证路由上收到 403。

我正在为网络套接字使用 Laravel websockets 包,并且我有以下设置

- Backend Laravel server ( on port 8000 )
- Laravel Websockets Server ( laravel is running on 8001 and websocket server on 6001 )
- Standalone Ionic React app ( on port 8100)

现在,当我尝试公共频道时一切正常,但是当我尝试私人频道时,它失败了。

在上面的 Laravel 套接字仪表板屏幕截图中,我可以看到已建立连接,因为这是与请求一起使用的相同 socketId。

我正在使用 Laravel Sanctum 进行身份验证。

PFB :- 我的客户端代码

const headers = {
    'Content-Type': 'application/json',
    Authorization: window.localStorage.getItem('token')
      ? `Bearer ${window.localStorage.getItem('token')}`
      : '',
    'Access-Control-Allow-Credentials': true,
  };
  const options = {
    broadcaster: 'pusher',
    key: 'abcsock',
    authEndpoint: 'http://localhost:8001/api/broadcasting/auth',
    authorizer: (channel, options) => {
      return {
        authorize: (socketId, callback) => {
          axios
            .post(
              'http://localhost:8001/api/broadcasting/auth',
              {
                socket_id: socketId,
                channel_name: channel.name,
              },
              { headers, withCredentials: true }
            )
            .then((response) => {
              callback(false, response.data);
            })
            .catch((error) => {
              callback(true, error);
            });
        },
      };
    },
    wsHost: '127.0.0.1',
    wsPort: 6001,
    encrypted: true,
    disableStats: true,
    enabledTransports: ['ws', 'wss'],
    forceTLS: false,
  };

来自 Laravel Websockets 服务器的代码

api.php 文件

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Broadcast;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Broadcast::routes(['middleware' => ['auth:sanctum']]);

广播服务提供者.php

namespace App\Providers;

use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Broadcast::routes(['middleware' => ['auth:sanctum']]);

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

新通知.php

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Broadcasting\PrivateChannel;

use App\AppNotification;
use App\User;

class NewNotification extends Notification
{
    use Queueable;

    public $notification;
    public $user;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(AppNotification $notification, User $user)
    {
        $this->notification = $notification;
        $this->user = $user;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        $notification = $this->notification;
        return [
            'id' => $notification->id,
            'title' => $notification->title,
            'description' => $notification->description,
            'button_text' => $notification->button_text,
            'is_read' => $notification->is_read,
            'created_at' => $notification->created_at,
            [
                'notification_for' => $notification->notifiable
            ]
        ];
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage($this->toArray($notifiable));
    }

    public function broadcastOn()
    {
        return new PrivateChannel('Notifications.' . $this->user->id);
    }
}

频道.php

<?php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('Notifications.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
}, ['guards' => ['sanctum']]);

我附上了我认为足以解释问题并让您排除故障的任何内容,但如果您需要更多信息,请询问。

任何帮助将不胜感激

4

2 回答 2

0

您是否为您的 channels.php 添加了身份验证?请参考这里: https ://laravel.com/docs/7.x/broadcasting#defining-authorization-routes 它是什么样子的?

我认为你做的一切都是正确的,但你没有授权你的路线。

于 2020-05-31T17:11:21.540 回答
0

我喜欢这个包,因为它是用 php 编写的,但它有点放弃了,还有很多问题没有解决。

该服务器的替代品是 laravel-echo-server(正如 laravel 文档所建议的那样),非常易于使用。 https://stackoverflow.com/a/61704796/7908390如果你可以使用 laravel-sockets,我很高兴看到一个新的例子

于 2020-05-31T11:41:48.600 回答