Laravel似乎忽略了通道.php中的授权回调

Laravel seems to ignore authorization callbacks in channels.php

提问人:Jheems 提问时间:11/17/2023 最后编辑:ProgmanJheems 更新时间:11/18/2023 访问量:31

问:

因此,我正在尝试向一个频道进行广播,并且我已经确保广播正常工作。现在我想确保该频道是私有的,只有授权用户才能收听。现在,根据文档,我可以通过创建授权回调并为该通道分配来做到这一点,因此,我使用命令创建了一个 Channel 类,并在如下所示中分配了通道类。php artisan make:channelroutes/channel.php

Broadcast::channel('private-admin.notifications.orders', OrderChannel::class);

channel 类的内容如下。

class OrderChannel
{
    /**
     * Create a new channel instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Authenticate the user's access to the channel.
     */
    public function join(User $user): array|bool
    {
        return false;
    }
}

您可能已经注意到,该方法将始终返回 false,这是故意的,因为我想看看如果未经授权的用户连接到通道会发生什么。我希望用户将无法收听或订阅它,但用户仍然可以收听该频道。我确信这一点,因为通知的代码会触发并显示通知。join

我做过的事情。

  • 取消注释,当我运行命令时,将返回所有内容。BroadcastServiceProvider::classconfig/app.phpchannels.phpphp artisan channel:list
  • 已清除应用程序缓存。

如果涉及任何人,我正在使用 Laravel Websockets 作为我的 websocket 服务器。

我是否做错了什么或错过了什么?

PHP 拉维尔

评论


答:

0赞 Jheems 11/17/2023 #1

因此,在发布此问题后,经过一段时间的挖掘。我发现,无论如何,我可用于广播的自定义身份验证端点将始终对用户进行身份验证,代码片段如下。/custom/broadcasting/auth

<?php

use BeyondCode\LaravelWebSockets\Apps\App;
use Illuminate\Broadcasting\Broadcasters\PusherBroadcaster;
use Illuminate\Http\Request;
use Pusher\Pusher;

class AuthenticateDashboard
{
    public function __invoke(Request $request)
    {
        /**
         * Find the app by using the header
         * and then reconstruct the PusherBroadcaster
         * using our own app selection.
         */
        $app = App::findById($request->header('x-app-id'));

        $broadcaster = new PusherBroadcaster(new Pusher(
            $app->key,
            $app->secret,
            $app->id,
            []
        ));

        /*
         * Since the dashboard itself is already secured by the
         * Authorize middleware, we can trust all channel
         * authentication requests in here.
         */
        return $broadcaster->validAuthenticationResponse($request, []);
    }
}

它是 laravel websockets 默认身份验证方法的 1:1 副本,可通过laravel-websockets/auth

我不知道该方法将始终对请求进行身份验证,并且我必须使用 laravel 提供的默认身份验证端点,该端点可通过 获得。我不得不对端点进行一些配置,因为它不接受我的请求。我必须通过 Laravel Echo 提供自定义身份验证器方法,以便它接受请求。validAuthenticationResponse()broadcasting/auth

我的如下,这允许我的前端成功向身份验证端点发出请求Broadcast::routes

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

话虽如此,我现在使用的是 laravel 提供的默认身份验证端点,它是端点,但根据我的配置,它现在是 .broadcasting/authapi/broadcasting/auth

广播不再忽视我的,现在工作完全正常。这只是我的配置错误。channels.php

评论

0赞 Jheems 11/18/2023
在发布此问题后不久,我添加了有关我提出的解决方案的更多信息。