在 laravel 11 中使用广播/身份验证来验证私有或存在通道的通道时显示 403 禁止错误
我使用JWT进行auth API登录并在广播路由中添加中间磨损
在channel.php中
Broadcast::routes(
['middleware' => [JwtMiddleware::class,CorsMiddelware::class]]
);
Broadcast::channel('chat', function ($user, $id) {
return true;
});
在 JwtMiddleware 中
public function handle(Request $request, Closure $next) :Response
{
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof TokenInvalidException){
return response()->json(['code' => 401,'message' => 'Token is Invalid']);
}else if ($e instanceof TokenExpiredException){
return response()->json(['code' => 401,'message' => 'Token is Expired']);
}else{
return response()->json(['code' => 401,'message' => 'Authorization Token not found']);
}
}
User::where('id',$user->id)->update(['last_seen_at' => now()]);
return $next($request);
}
当点击/广播/验证时
显示错误状态 403
我在这上面花了很多时间,在它起作用之前我将端点添加到了
api
路线中。
Route::post('/broadcasting/auth', [BroadcastController::class, 'authenticate'])
不要忘记导入类:
Illuminate\Broadcasting\BroadcastController
确保将其放入
auth:sanctum
中间件组
new Echo({
broadcaster: "reverb",
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: import.meta.env.VITE_REVERB_PORT,
wssPort: import.meta.env.VITE_REVERB_PORT,
forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? "https") === "https",
authEndpoint: import.meta.env.VITE_API_PATH + "/broadcasting/auth",
enabledTransports: ["ws", "wss"],
auth: {
headers: {
Authorization: `Bearer ${this.token}`,
},
},
});
注意:我向 Echo 实例添加了另一个键:
authEndpoint
。