Comments (28)
@petervmeijgaard I think I've figured it out. The Authorization header isn't sent by Echo, its sent by Pusher. Setting the Authorization header in Echo only sets the header when the Pusher instance is constructed.
To set the Authorization header on the fly, you need to set the header on the Pusher object:
Echo.connector.pusher.config.auth.headers['Authorization'] = 'Bearer token';
I'm using the vue-auth plugin, so I'm able to add the header by overriding the _setHeaders function. You should also be able to set the header via a vue-resource interceptor.
from echo.
Setting the pusher config directly did not work for me (and I'm not using vue-resource) -- but this solution worked: tlaverdure/laravel-echo-server#129 (comment)
In my case I'm, using vue-echo on top of Echo, but the config block should work directly in Echo as well. For example:
Vue.use(VueEcho, {
broadcaster: 'pusher',
key: PUSHER_KEY,
auth: {
headers: {
Authorization: 'Bearer ' + BEARER_TOKEN,
},
},
});
...and setting:
Broadcast::routes(['middleware' => ['auth:api']]);
...in BroadcastServiceProvider as well.
from echo.
To set on the fly for socket.io:
Echo.connector.options.auth.headers['Authorization'] = 'Bearer ' + token
from echo.
This works for me:
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001',
auth: {
headers: {
'Authorization': 'Bearer ******'
}
}
});
from echo.
Echo.connector.options.auth.headers.Authorization = 'Bearer token';
from echo.
Soultion to Common Problems faced by many users while setting up Laravel Echo
https://gist.github.com/rauschmerscen/2f2265976d59267f3bfccb339b27be44
from echo.
@petervmeijgaard Have you been able to get the Authorisation header set? I'm also running into this issue.
from echo.
@kubacode Nope, I still haven't figured out how to get it working 😞
from echo.
Need a special method in Echo instance to set parameters (at least headers
and authEndpoint
) on the fly.
from echo.
@chimit make a PR then.
from echo.
Hello, I had the same problem ,and it took me some time to figure it out. I was using pusher as my broadcasting driver. The first step required changing broadcasting middleware to Broadcast::routes(['middleware' => ['api', 'jwt.auth']]); because I am using jwt authentication.
This required sending the jwt token from the client-side upon registering to laravel-echo along with changing the authEndpoint as I was using a virtual host.
The resulting laravel-echo configuration is as follows:
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'PUSHER_KEY',
authEndpoint :'http://virtual_host/broadcasting/auth',
auth: {
headers: {
Authorization: 'Bearer ' + CLIENT_TOKEN,
}
},
cluster: 'PUSHER_CLUSTER',
encrypted: true
});
I hope my answer will help you.
from echo.
I have SPA with JWT AUTH.
When i join to presence channel i'm registering Echo in the component.
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001',
auth: {
headers: {
Authorization: 'Bearer ' + token // user token after auth
}
}
})
here is component code:
methods: {
listenForBroadcast () {
const token = this.$auth.token()
if (typeof io !== 'undefined' && token) {
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001',
auth: {
headers: {
Authorization: 'Bearer ' + token
}
}
})
} else {
console.log('token error')
}
window.Echo.join('test')
.here(users => {
console.log(users, 'users')
})
.joining(user => {
console.log(user, 'joining user')
})
.leaving(user => {
console.log(user, 'leaving')
})
.listen('MessagePushed', e => {
console.log(e)
})
},
},
mounted () {
this.listenForBroadcast()
}
but i'm thinking it's not best practice.
Is there something wrong i'm doing?
from echo.
I had the same issue. But mine was 405 method not allowed.
I added added App\Providers\BroadcastServiceProvider::class provider in the config/app.php file.
Then I entered php artisan config:cache command.
from echo.
Hi Guys,
I'm facing similar issue using Nuxt js, I can't get any events broadcasted on frontend side.
It's have been days so far trying to get it working, i have looked entire googling but nothing is out there envolving laravel-echo with pusher-js using Nuxtjs.
And the funny thing is that I got the same scripts working on the demo side, which I made for testing, using Laravel with Vuejs setup without any API, it works properly.
But now I've created any standalone Nuxtjs project and using Laravel for Backend, and I can't get the events working.
If I check on Pusher Console, I get the broadcast, but nothing is firing on the frontend,
tried all tricks, renaming the Namespace of Echo, using . on Event but nothing works.
Below the code
Echo Integration
`import LaravelEcho from "laravel-echo"
export default ({ app, redirect }) => {
const token = localStorage.getItem('auth._token.local')
window.Pusher = require('pusher-js');
window.Echo = new LaravelEcho({
authEndpoint: `${process.env.apiUrl}accounts/broadcast`,
broadcaster: 'pusher',
key: 'mykeysgoeshere',
cluster: 'eu',
auth: {
headers: {
Authorization: `${token}`
},
},
});
channels.php
Broacast call
Broadcast Provider
One of the thing which I'm not sure about all of this is how to check broacasting/auth which above I just check if the user is Authenticated or not.
But any help will be appreciated, or any advice if someone tried echo with pusher using Nuxtjs.
from echo.
Hey @jjoao07, hope I can help you a bit.
I think your biggest issue, is trying to set up a window.Echo
instance, in your js App.
Good chance you're calling things too early in the lifecycle to hook up into it properly...
--
Here's an example of how I'm working pusher on my app in nuxt.js. I've set it up as a Vuex Module, so I can easily call it and check instances in my app...
For now, I've dealt with logged in/out states as different echo instances. But I'm working on trying to solve that problem too....
https://gist.github.com/unr/345fe5c9daf7e5daffa1f23842d2c9ab
You can see how I've tried to set up my module, and call it from my main layouts in this gist.
I would ignore some of my
refresh-csrf
stuff in this gist tho... likely don't need it. It's a poor route to refresh it on the frontend in really fringe cases.
from echo.
Hi @unr , thanks for your sharing
Will have a look and let u know
from echo.
Hi @unr
Sorry for not coming back, I have been trying to get done other stuff in the project, and from yesterday, started working on this again.
I have checked your repo, but I'm still not getting it in right way.
I'm getting an error like Do not mutate vuex store state outside mutation handlers.
while trying to commit the instance to the state, and I have no idea why this happening.
below is what I got so far
https://gist.github.com/jjoao07/afe39be3d8b93971e7f02db22d0d40a4
And I'm dispatching this like this this.$store.dispatch('echoModule/createPrivate')
So not sure what I'm missing out in order to get Do not mutate vuex store state outside mutation handlers
I really need to fix this issue, and driving me crazy right now.
from echo.
Hmm, I haven't run into that specific error with this setup @jjoao07
Are you sure that it is being caused by the createPrivate call, and not another vuex call?
Otherwise.... Maybe it's where we return a promise, and commit
inside that, that vuex doesn't like. 🤔
from echo.
Hi @unr , Yes I'm sure about it. the problem is with that commit,
If I comment the commit, the script run, but I don't have how to access it from outside.
so not sure how I can access Echo instance, without committing or to run it without getting vuex error
from echo.
Oh, I see what you're doing.
You seem to call this.$store.dispatch('echoModule/createPrivate')
directly, but what should happen is you try to join a channel, and that creates the instance for you.
In your version of the gist, you only have connectToConversationChannel
, which uses the private instance.
In a perfect world, calling this.$store.dispatch('echoModule/connectToConversationChannel')
create the instance, and then connect to it.
You should then have a method to leave those channels.
It sounds like you may be doing something like this, instead of the above.
- create instance via
this.$store.dispatch('echoModule/createPrivate')
- try to join a channel via
this.$store.state.echoModule.instance.public()
from echo.
@unr Okay thanks, will try out in the morning, and let u know.
For now, I was just trying to see if I can listen to the event and console.log, so that I could move on and implements the leave and other stuff.
Perhaps is your events namespace located in Events dir like App\Events\EventsClass or something like App\Events\dir\EventClass, because I'm also guessing to have some issues with namespacing, but I have tried to listen to it like below.
Echo.private('channel') .listen('EventClass', (e) =>{ console.log(' I couldn't get nothing like this and moved on to namespace with . like below') })
Echo.private('channel') .listen('.EventClass', (e) =>{ console.log('Even this also didn'\t worj and tried last one') })
Echo.private('channel') .listen('.App.Events.EventClass', (e) =>{ console.log(' and without success') })
from echo.
Personally, my private channels are user specific. I access them like
state.instance.private(`User.${uuid}`)
.notification((notification) => console.log(notification));
For my public channels,
state.instance.channel('live')
.listen('MatchScoreChanged', notification => dispatch('handleMatchScoreChanged', notification));
(I'm not a pro with backend/laravel... I'm just a lowly frontend! Not sure on what/why you need to listen to something specific)
In my example,
state.instance
==Echo
in your example.
from echo.
@unr okay I got it.
I'm pro on backend, there different reasons for the channels, I got one for specific users and some for different broadcast. but will review nice tomorrow, otherwise, I may need your assistance with this, and we take from there.
from echo.
Hi @unr I just fixed it. but I made it on my way, not in your way via vuex. the main issue was the endpoint url
I was using it under API route which was wrong. below is a gist solution
https://gist.github.com/jjoao07/ca233477b495ed8188fb618823108624
Thanks, @unr for your help and feedback
from echo.
Glad to see your problem solved @jjoao07
And thanks for sharing your solution as well. :)
from echo.
Going to close this as this discussion has gone off topic quite a bit.
from echo.
How do you obtain the bearer token ?
from echo.
Hey @jjoao07 you can check your BroadcastServiceProvider.php on App/Providers/BroadcastServiceProvider.php then make your Broadcast::routes(['middleware' => ['auth:users']]) something like this. In my case, it works!
from echo.
Related Issues (20)
- #listenToAll for NullConnector HOT 1
- #encryptedPrivate does not work with NullConnector HOT 1
- PresenceChannel interface missing 'Whisper' method HOT 2
- Implement `.listenOnce` and `.isListening` HOT 1
- [Bug] PresenceChannel interface missing 'Whisper' method HOT 2
- Nuxtjs + VUE 2 to update vue 3 + vite not working echo HOT 2
- Always got pusher ouput while using socket.io HOT 1
- Not subscribing to Echo when you open SPA as PWA from Homescreen HOT 4
- All the names of the events must be prefixed with a dot HOT 1
- Uncaught TypeError: event is undefined HOT 2
- Connection fails in Chrome, works just fine in FF HOT 1
- Export connectors and channels alongside with Echo and abstract classes HOT 2
- Laravel Echo with Socket.io HOT 1
- Centrifugo Connector HOT 1
- Fatal error when using channel.listen HOT 3
- Leave channel and disconnect right after HOT 1
- listen method does not work HOT 1
- Dont can get the returns of websocket
- dont cant get returns in console.log of the websocket, HOT 2
- ReferenceError: Property 'Pusher' doesn't exist HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from echo.