tlaverdure / laravel-echo-server

Socket.io server for Laravel Echo
MIT License
2.65k stars 510 forks source link

Client could not be authenticated 403 status #427

Open gecas opened 5 years ago

gecas commented 5 years ago

Hello, I am using laravel echo with presence channel. My user is logged with with Laravel default auth but I cannot get it to work. My code:

channels.php file:

Broadcast::channel('forum-created', function ($user) { return $user; });

bootstrap.js:

window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });

Event:

public function broadcastOn() { return new PresenceChannel('forum-created'); }

In my vue component:

window.Echo.join('presence_laravel_database_forum-created').listen('ForumCreatedEvent', ({ forum }) => { console.log('listened'); });

Laravel echo server config json:

{ "authHost": "http://laravel.echo", "authEndpoint": "/broadcasting/auth", "clients": [ { "appId": "", "key": "" } ], "database": "redis", "databaseConfig": { "redis": {}, "sqlite": { "databasePath": "/database/laravel-echo-server.sqlite" } }, "devMode": true, "host": null, "port": "6001", "protocol": "http", "socketio": {}, "sslCertPath": "", "sslKeyPath": "", "sslCertChainPath": "", "sslPassphrase": "", "subscribers": { "http": true, "redis": true }, "apiOriginAllow": { "allowCors": false, "allowOrigin": "", "allowMethods": "", "allowHeaders": "" } }

Everything was working well with simple public channel but now for some reason user is not authenticated although it is logged in to the system. What might be the issue here?

appdrops commented 5 years ago

@gecas

Looks like you have to authenticate the user with Laravel Echo. In your bootstrap.js file you need something that looks like this:

 if (typeof io !== 'undefined') {
   window.Echo = new Echo({
    namespace: 'App\\Events',
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001',
    authEndpoint : window.location.hostname + '/broadcasting/auth',
    auth: {
      headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('access_token')
          }
    }
   });
 } else {
  console.log('token error')
}