Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel authorization for Broadcast channels not working

I am trying to integrate chat into a webapp using Laravel 5.4 (backend) and Angular 2 (frontend). I have a unqiue Broadcast channel that emits a message to a user. Each user has their own channel which is chat-{uuid} with uuid being a unique ID in a chat table which also stores the userID of the user who can access that channel. The problem is that the Authorization callback is never called so any user can access the channel if they know the uuid. I'm not sure what I'm doing wrong

channels.php

// This authorization is never called 
Broadcast::channel('chat-{uuid}', function ($user, $uuid) {
    return false; 
});

NewMessage.php event

protected     $message;

public function __construct($message)
{
    $this->message = $message;
}

protected function prepareData()
{
    return [
        'chatID'                => $this->message->chatID,
        'userID'                => $this->message->builderID,
        'message'               => $this->message->message,
        ];

}

public function broadcastWith()
{
    return [
        'message' => $this->prepareData(),
    ];
}

public function broadcastAs()
{
    return 'new.message';
}

public function broadcastOn()
{
    return new PrivateChannel('chat-'.$this->message->chatID);
}

BroadcastServiceProvider.php

public function boot()
{
    Broadcast::routes( [ 'middleware' => [ 'api', 'auth.jwt' ] ] );
    require base_path('routes/channels.php');
}

Connecting to the broadchannel on the frontend (Messages are being recieved)

Component.ts

  window['Echo'] = new Echo({
    broadcaster: 'socket.io',
    host: 'http://app.test:6001',
    auth:
      {
        headers:
          {
            'Authorization': 'Bearer ' + this.auth.jwt
          }
      }
  });

window['Echo'].private(`chat-${this.chatUUID}`)
  .listen(".new.message", (data) => {
    this.messages.data.push(data.message);
  });
like image 480
ghan Avatar asked Jan 17 '18 15:01

ghan


1 Answers

Apparently the problem is not on programming side but related to your web server configuration (or web socket server). I think you always got private channel authenticated but not through /broadcusting/auth simple because response gives you 200 code. As you can see in laravel-echo-server sourse channels get authentication residually. So, your routes/channels may not be involved to the process. Furthermore if you exclude BroadcastServiceProvider from the configuration perhaps you will get private channel being authenticated anyway.

If everything indicated like that I would suggest take a look to the web-server configuration especially if you use SSL.Alternative SSL implementation and laravel-echo-server.json of course.

like image 65
Yuri Shekhovtsov Avatar answered Nov 14 '22 12:11

Yuri Shekhovtsov