1

我已经使用 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

任何帮助将不胜感激

4

1 回答 1

1

好吧,这很有趣。我决定检查 laravel-echo-server 如何请求“广播/身份验证”以及它如何处理该请求的响应。

你可以看看这里:https ://github.com/tlaverdure/laravel-echo-server/blob/master/src/channels/private-channel.ts

所以 laravel-echo-server 如果广播/认证的响应码是 200 则返回 true,如果响应码不是 200 或请求出错则返回 false。

这里的问题是,当您向通过护照身份验证处理的 laravel api 路由发送请求时,它确实返回“未经身份验证”消息但没有 401 代码,因此 laravel-echo-server 认为请求成功并允许用户加入频道。

解决方案:

  1. 使用 Passport 未经身份验证的响应返回 401 代码
  2. 通道认证中间件

使用 Passport 未经身份验证的响应返回 401 代码

projectdir\app\Exceptions Handler.php

...
use Illuminate\Auth\AuthenticationException;

...
public function render($request, Exception $exception)
{
    if($exception instanceof AuthenticationException){
        return response()->json(['message' => $exception->getMessage()], 401);
    }else{
        return response()->json(['message' => $exception->getMessage() ]);
    }

    return parent::render($request, $exception);
}

通道认证中间件

php artisan make:middleware [名称]

projectdir\app\Http\Middleware [名称].php

use Closure;
use Illuminate\Support\Facades\Auth;

class SocketAuth
{

    public function handle($request, Closure $next)
    {
        $user = Auth::User();

        if($user !== null){
            if($request->channel_name == "private-user.".$user->id){
                return $next($request);
            }else{
                return response()->json(["message" => "Unauthenticated."], 401);
            }
        }

        return response()->json(["message" => "Unauthenticated."], 401);
    }
}

广播服务提供者

Broadcast::routes(["prefix" => "api", 'middleware' => ['auth:api', 'SocketAuth']]);

注册中间件

projectdir\app\Http Kernel.php

protected $routeMiddleware = [
    ...
    'SocketAuth' => \App\Http\Middleware\SocketAuth::class,
];

Laravel-Echo-服务器配置

"authEndpoint": "/api/broadcasting/auth",

结果

  1. 未经身份验证的 401 - (Laravel-Echo-Server False) 开启:[来自客户端的请求中不存在令牌,请求的用户频道!== 正在请求用户的频道]

  2. Authenticated 200 - (Laravel-Echo-Server True) On : [令牌存在于来自客户端的请求和请求的用户频道 == 请求用户的频道]

您可以将验证用户的逻辑应用于中间件中的通道。

于 2020-07-14T13:34:00.990 回答