Answer the question
In order to leave comments, you need to log in
How to allow only authorized users to connect to laravel-echo-server (redis + socket.io) in vue components?
There is an application with correspondence between users and the ability to publish articles in real time (on websocket). SPA application , there is Laravel Passport authentication through a token , so a token must be attached to each request in the header .
Upon authorization in VUEX , a mutation is invoked that stores the token in local storage and changes the state of whether the user is logged in. ( state.isLoggedIn )
loginUser(state, data) {
state.isLoggedIn = true;
localStorage.setItem('token', data.access_token);
},
axios.interceptors.request.use(function (config) {
config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
return config;
}, function (err) {
return Promise.reject(err);
});
import Echo from "laravel-echo"
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001',
auth: {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
},
},
});
Broadcast::routes(['middleware' => ['auth:api']]);
const app = new Vue({
el: '#app',
router,
store,
components: {
MainApp
},
});
watch: {
isLoggedIn: function (val) {
if (val === true) {
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001',
auth: {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
},
},
});
window.Echo.private('room.' + this.user_id)
.listen('PrivateChat', ({data}) => {
...
}
})
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question