我已经使用 laravel-echo 设置了 socket.io 来加入并收听 laravel 广播频道。公共频道运行良好,因为它们不需要任何身份验证。私人频道没有按预期工作,我可以在不传递授权令牌的情况下使用 socket.io 客户端加入任何私人频道。
Socket.io 客户端
window.Echo = new Echo({
host: "http://127.0.0.1:6001",
auth:{
headers: {
Accept: 'application/json',
Authorization: 'Bearer ',
},
},
broadcaster: 'socket.io',
});
window.Echo.private('user'+"."+userid)
.listen('Notification', (e) => {
console.log(e);
})
Laravel-Echo-服务器配置
{
"authHost": "http://127.0.0.1:8000",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {
"port": "6379",
"host": "localhost"
},
"sqlite": {}
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"secureOptions": 67108864,
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": true,
"allowOrigin": "localhost",
"allowMethods": "GET, POST",
"allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}
}
通道路线
Broadcast::channel('user.{userId}', function ($user, $userId) {
return (int) $user->id === (int) $userId;
});
广播服务提供者
Broadcast::routes(['middleware' => ['auth:api']]);
授权配置
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
127.0.0.1:8000/broadcasting/auth 无令牌访问时响应
{"message":"Unauthenticated."}
Laravel-Echo-服务器
[4:50:17 PM] - Preparing authentication request to: http://127.0.0.1:8000
[4:50:17 PM] - Sending auth request to: http://127.0.0.1:8000/broadcasting/auth
[4:50:17 PM] - LtnbMInYDGa_QMMcAAAA authenticated for: private-user.1
[4:50:17 PM] - LtnbMInYDGa_QMMcAAAA joined channel: private-user.1
所以我的猜测是 laravel-echo-server 在响应“未验证”时没有返回 false
任何帮助将不胜感激