You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pusher-websocket-react-native连接私有频道返回403错误求助

React Native中Pusher私有频道403认证错误解决方法

核心问题本质

私有频道订阅时的403错误,是因为Laravel的broadcasting/auth端点没收到有效的用户授权Token,导致后端拒绝认证请求。Web端Pusher.js可直接配置auth对象带Token,但React Native的Pusher库需要调整初始化配置来传递认证头。

解决方案:初始化Pusher时添加认证头

修改你的pusher.init配置,新增auth参数,把用户的Bearer Token放进请求头:

const connect = async () => {
    try {
        await pusher.init({
            apiKey: "c278b3fbeeb3*******",
            authEndpoint: 'https://3ce2-154-118-34-153.ngrok.io/broadcasting/auth',
            cluster: "mt1",
            // 添加认证头配置
            auth: {
                headers: {
                    Authorization: `Bearer ${user?.token}` // 替换为实际的用户Token
                }
            },
            onEvent: (event) => {
                console.log(event);
            },
            onSubscriptionSucceeded,
            onDecryptionFailure: (event) => {
                console.log('onDecryptionFailure', event);
            }
        });
        await pusher.connect();

        let myChannel = await pusher.subscribe({
            channelName: "my-channel", onEvent: (event) => {
                console.log(`onEvent: ${event}`);
            }
        });

        let privateChannel = await pusher.subscribe({
            channelName: `private-User.${user?.id}`, onEvent: (event) => {
                console.log(`onEvent: ${event}`);
            }
        });
        console.log(privateChannel);


    } catch (e) {
        console.log('ERROR: ' + e);
    }
};

后端配置验证

确保Laravel后端的广播认证路由用对了中间件:

  1. 打开app/Providers/BroadcastServiceProvider.php
  2. 确认boot方法里,广播路由的中间件是auth:api(适配API Token认证):
Broadcast::routes(['middleware' => ['auth:api']]);

原理说明

React Native的Pusher库订阅私有频道时,会自动向你配置的authEndpoint发送POST请求,携带频道名称等参数。通过在auth.headers里加Authorization头,后端Laravel就能通过auth:api中间件验证用户身份,返回合法的Pusher认证签名,完成私有频道订阅。

内容的提问来源于stack exchange,提问作者Nathaniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:33:21