Laravel /broadcasting/auth 总是失败,并显示 403 错误

2022-08-30 19:01:02

我最近深入研究了Laravel 5.3的Laravel-Echo和Pusher组合。我已经成功地设置了公共频道,并转向了私人频道。我在 Laravel 从 /broadcasting/auth 路由返回 403 时遇到问题,无论我采取什么措施来尝试授权该操作(最多,包括使用简单的返回 true 语句)。谁能告诉我我做错了什么?

App/Providers/BroadcastService Providers.php:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Broadcast::routes();

        /*
         * Authenticate the user's personal channel...
         */
        Broadcast::channel('App.User.*', function ($user, $userId) {
            return true;
        });
    }
}

resources/assets/js/booststrap.js:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'My-Key-Here'
});

window.Echo.private('App.User.1')
    .notification((notification) => {
        console.log(notification.type);
    });

我可以在我的 Pusher 调试控制台中看到事件及其有效负载,一旦它到达身份验证路由,它就会失败。


答案 1

错误 403 /broadcasting/auth 使用 Laravel 版本 > 5.3 & Pusher,您需要更改 resources/assets/js/bootstrap 中的代码.js

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your key',
    cluster: 'your cluster',
    encrypted: true,
    auth: {
        headers: {
            Authorization: 'Bearer ' + YourTokenLogin
        },
    },
});

在应用程序/提供商/广播服务提供商.php中,替换

Broadcast::routes()

Broadcast::routes(['middleware' => ['auth:api']]);

Broadcast::routes(['middleware' => ['jwt.auth']]); //if you use JWT

Broadcast::routes(['middleware' => ['auth:sanctum']]); //if you use Laravel 

它对我有用,我希望它能帮助你。


答案 2

我通过创建通道路由来解决它。

在路由>通道中创建授权通道.php

Broadcast::channel('chatroom', function ($user) {
    return $user;
});

请参阅文档 : https://laravel.com/docs/5.4/broadcasting#authorizing-channels

谢谢


推荐