Ошибка PrivateChannel 403 Laravel Echo Pusher Laravel Локальная настройка веб-сокетов - PullRequest
2 голосов
/ 28 мая 2020

Я получаю 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)

Теперь все работает, когда Я пытаюсь использовать канал Publi c, но когда я пытаюсь использовать частный канал, он терпит неудачу.

на скриншоте выше панели управления сокетами 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 сервера веб-сокетов

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

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

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

Я приложил все, что, по моему мнению, было достаточно, чтобы объяснить проблему и устранить неполадки, но если вам нужно что-то еще, спросите.

Любая помощь будет оценена

Ответы [ 2 ]

0 голосов
/ 31 мая 2020

Вы добавили аутентификацию для своих каналов. php? Пожалуйста, обратитесь сюда: https://laravel.com/docs/7.x/broadcasting#defining -authorization-routes Как это выглядит?

Я думаю, вы все делаете правильно, но вы не авторизовали свои маршруты.

0 голосов
/ 31 мая 2020

Мне понравился этот пакет, потому что он был написан в php, но его разновидность отказалась и множество проблем, которые не решены.

Альтернативой этому серверу является laravel -echo-server (как laravel docs рекомендует) очень прост в использовании. { ссылка } подробнее, если вы можете работать с laravel -сокетами. Я рад видеть новый пример

...