Laravel 8 授权私有广播频道
如果你的单页面应用需要通过 private / presence broadcast channels 进行身份认证,你需要在你的 routes/api.php
文件中调用 Broadcast::routes
方法:
Broadcast::routes(['middleware' => ['auth:sanctum']]);
接下来,为了使 Pusher 的授权请求成功,你需要在初始化 Laravel Echo 时提供自定义的 Pusher authorizer
。这可以让你的应用程序将 Pusher 配置为 为了跨域请求正确配置的 axios
实例 properly configured for cross-domain requests:
window.Echo = new Echo({
broadcaster: "pusher",
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
key: process.env.MIX_PUSHER_APP_KEY,
authorizer: (channel, options) => {
return {
authorize: (socketId, callback) => {
axios.post('/api/broadcasting/auth', {
socket_id: socketId,
channel_name: channel.name
})
.then(response => {
callback(false, response.data);
})
.catch(error => {
callback(true, error);
});
}
};
},
})