发送POST请求到http://localhost:8000/broadcasting/auth时返回403(禁止访问)错误。该错误与身份验证相关。

4

我正在尝试让我的应用连接到一个私有频道的 Pusher。

但是我在控制台中收到以下错误信息:

POST http://localhost:8000/broadcasting/auth 403 (禁止访问)

app.js

 /**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('payment', require('./components/Payment.vue'));
Vue.component('form-ajax', require('./components/FormAjax.vue'));
Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

    Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

const app = new Vue({
    el: '#app'
});

Echo.private(`articles.admin`)
    .listen('ArticleEvent', function(e)  {
        console.log(e);
    });

错误

可能导致错误的原因以及如何解决它。

7个回答

7

当使用 Laravel 版本 > 5.3 和 Pusher 时,访问 /broadcasting/auth 时可能会出现错误 403。此时,您需要在 resources/assets/js/bootstrap.js 中更改您的代码。

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

app/Providers/BroadcastServiceProvider.php 文件中进行更改:

Broadcast::routes()

使用

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

或者

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

这对我很有效,希望它也能帮助到你。


我们如何在BroadcastServiceProvider.php中使用自定义身份验证?@Alex - Bilal Rabbi
3
@Alex,“YourTokenLogin”是什么,我该如何在那里实现它? - Anonymous Chatbox

3

你尝试过自定义你的authEndpoint吗?

这个东西在我的端上运作良好。

bootsrap.js

window.Echo = new Echo({
    broadcaster: 'pusher',
    // ...
    authEndpoint: '/custom/endpoint/auth'
});

2
在我的情况下,我使用了一个自定义的身份验证守卫,这导致了问题。
我已经添加了中间件来传递我的自定义身份验证守卫,这解决了问题。
public function boot()
{
    Broadcast::routes(['middleware' => 'auth:admin']);

    require base_path('routes/channels.php');
}

这个链接更详细地解释了正在发生的事情。


0

我曾经遇到过同样的问题,但这个技巧拯救了我的生命。

进入 api.php

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

0

我将下面的代码添加到routes/web.php中,它可以正常工作。

 Route::post('/broadcasting/auth', function () {
    return Auth::user();
 });

0
也许你有多个守卫。如果是的话,你需要在BroadcastServiceProvider中的Broadcast::routes()中指定你的守卫授权中间件,就像这样:
Broadcast::routes(['middleware' => ['web','auth:admin']]);

更多信息请参考:https://github.com/laravel/framework/issues/16151

-2

我通过仔细检查频道名称中的拼写错误解决了我的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接