1

I am building a react native application with laravel api, and pusherjs websocket. But i am getting the 403 error on private channel.

I am quite familiar with the Pusher.js for web, and i know that when it throws this error, its an authentication error, all i need to add is the auth object that contains the token to the pusher class when initialized.

However this package doesn't seem to have a provision for authentication header for private channel, and I cant seem to figure out how to add the authorization token to the Pusher.

My code snippet:

    const connect = async () => {
        try {
            await pusher.init({
                apiKey: "c278b3fbeeb3*******",
                authEndpoint: 'https://3ce2-154-118-34-153.ngrok.io/broadcasting/auth',
                cluster: "mt1",
                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);
        }
    };
Nathaniel
  • 53
  • 1
  • 5
  • Have you gotten an answer or solution to this? I’m stuck with same issue @Nathaniel – Nate Dec 31 '22 at 21:21

1 Answers1

0

Here is a link to the pusher-websocket-react-native example app. If you look at the onAuthorizer method, you'll notice it performs a fetch with the headers and body. In this case, you would include whatever authentication header is required for you to connect.

Something like:

const response = await fetch('some_url', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': <YOUR_AUTHORIZATION_TOKEN>
      },
      body: JSON.stringify({
        socket_id: socketId,
        channel_name: channelName,
      }),
    });

Note: in my experience, I removed the authEndpoint field and relied on onAuthorizer to handle things. Your results may vary.

Tony Xu
  • 194
  • 2
  • 9