Flutter + Laravel Websocket + Pusher Replacement (Valet Secure) - laravel

I'm using Beyondco Larevel Websockets on my Laravel Backend, and using pusher_client and laravel_echo on my Flutter frontend.
I've been trying to connect from my ios simulator into my Laravel Backend host, which is using valet secure, but failing.
My Flutter connections:
PusherClient getPusherClient(String token) {
PusherOptions options = PusherOptions(
host: 'my-local-server.test',
wsPort: 6001,
wssPort: 6001,
cluster: DotEnv.env['PUSHER_APP_CLUSTER'],
encrypted: true,
auth: PusherAuth('https://my-local-server.test/api/broadcasting/auth',
headers: {'Authorization': 'Bearer $token'})
);
return PusherClient(DotEnv.env['PUSHER_APP_KEY'], options,
enableLogging: true, autoConnect: false);
}
pusherClient = getPusherClient(token);
pusherClient.connect();
pusherClient.onConnectionStateChange((state) {
print(
"previousState: ${state.previousState}, currentState: ${state.currentState}");
});
pusherClient.onConnectionError((error) {
print(error.message);
});
From https://my-local-server.test/laravel-websockets I never see the requests from Flutter, but if I fire an event from my Laravel backend, it gets logged.
Please help me with what's wrong in my setup, why I can't connect to my SSL valet server running laravel-websocket from my Flutter application.

Related

how to send the cookie from Apollo Studo

my environment:
Apollo server version 3.8.1
Apollo express version 3.8.1
I allowed the cors
server.applyMiddleware({
app,
cors: {
credentials: true,
origin: [
`http://localhost:${config.gql.port}/graphql`,
'https://studio.apollographql.com'
]
},
onHealthCheck: () => healthCheck()
});
I set the trust proxy
export const app = express();
if (process.env.NODE_ENV !== 'production') {
app.set("trust proxy", true);
console.log("set trust proxy");
}
I opened the Including cookie from the Apollo studio.
I set the header
"x-forwarded-proto": "https"
But when I use ctx.req.cookies, I got undefined
I try from this blog.
https://blog.devgenius.io/graphql-apollo-studio-and-cookies-5d8519d0ca7e

Laravel Sanctum & broadcasting with Pusher.js (401, 419 error)

For 4 days I have been trying to connect to a private channel. Combined all the possible properties that I could find, but nothing solved the problem. A deeper understanding of the issue is needed.
I am creating an application using Laravel Sanctum, Nuxt.js, Nuxt-auth.
I need to connect to a broadcasting private channel.
At first I tried to create a connection using the #nuxtjs/laravel-echo package.
After long attempts to configure the connection, I found that the PisherConnector instance is not even created if I set the authModule: true (Public channels connect perfectly). Having discovered that this package is not actively supported and the fact that I do not have full access to connection management, I decided to abandon it.
Then I tried to set a connection using Laravel-echo and then directly through Pusher. Nothing works, I get either a 401 or 419 error.
I have a lot of questions and no answers.
When do I need to use laravel-echo-server?
When do I need to use pusher/pusher-php-server?
In which case do I need to connect to broadcasting/auth, and in which to api/broadcasting/auth? My frontend runs on api/login, but I don't want to provide external access to my API.
I added Broadcast::routes(['middleware' => ['auth: sanctum']]) to my BroadcastServiceProvider and to routes/api.php too (for testing). I'm not sure here either. Broadcast::routes(['middleware' => ['auth: api']]) may be needed or leave the default Broadcast::routes()?
What are the correct settings for configs: config/cors.php, config/broadcasting.php, config/sanctum.php, config/auth.php? What key parameters can affect request validation?
Should I pass CSRF-TOKEN to headers? I have tried in different ways.
When do I need to set the encrypted:true option?
What middleware should be present in the Kernel and what might get in the way?
If I set authEndpoint to api/broadcasting/auth I get 419 error (trying to pass csrf-token does not help). If I set authEndpoint to broadcasting/auth I get 401 error.
I do not provide examples of my code, since I tried all the options in all configs. I also tried to learn the documentation for my issue on the Laravel site, Pusher.js, looked at examples. Various examples mention some options but not others, and vice versa.
I would be glad to any advice.
I had the same issue as you. I had forgot to add the BroadCastingServiceProvider in my /config/app.php.
The app/Providers/BroadcastServiceProvider.php now looks like this:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Broadcast::routes(['middleware' => ['api', 'auth:sanctum']]);
require base_path('routes/channels.php');
}
}
I have not added Broadcast::routes to any other route file.
This is what my Laravel Echo init looks like:
new Echo({
broadcaster: 'pusher',
key: 'korvrolf',
wsHost: window.location.hostname, // I host my own web socket server atm
wsPort: 6001, // I host my own web socket server atm
forceTLS: false,
auth: {
withCredentials: true,
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
}
})
Without the CSRF-token the endpoint will return the 419 status response.
In my index.blade.php for my SPA I print out the CSRF-token:
<script>
window.Larvel = {
csrfToken: "{{ csrf_token() }}"
}
</script>
Now, the /broadcast/auth endpoint returns a 200 response.
I had the same issue with Laravel & pusher.
I have fixed using decodeURIComponent and moving BroadCast::routes(['middleware' => ['auth:sanctum']]) to routes/api.php from BroadcastServiceProvider.php
Also, add withCredentials = true.
const value = `; ${document.cookie}`
const parts = value.split(`; XSRF-TOKEN=`)
const xsrfToken = parts.pop().split(';').shift()
Pusher.Runtime.createXHR = function () {
const xhr = new XMLHttpRequest()
xhr.withCredentials = true
return xhr
}
const pusher = new Pusher(`${process.env.REACT_APP_PUSHER_APP_KEY}`,
{
cluster: 'us3',
authEndpoint: `${process.env.REACT_APP_ORIG_URL}/grooming/broadcasting/auth`,
auth: {
headers: {
Accept: 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'X-XSRF-TOKEN': decodeURIComponent(xsrfToken)
}
}
})
I hope this helps a bit.

Laravel/Vuejs and Pusher Not Connecting to Private Channel on Heroku

I have a laravel/vuejs realtime application, works on my local environment but when I deploy to heroku /auth/broadcast shows unsual response,
bootstrap.js
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': window.csrf_token
};
const JWTtoken = `Bearer ${localStorage.getItem('access_token')}`
import Echo from 'laravel-echo';
// import Pusher from 'pusher-js';
window.Pusher = require('pusher-js');
Pusher.logToConsole = true;
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true,
encrypted: true,
auth: {
headers: {
'Authorization' : JWTtoken,
}
}
});
In vue.js component
Echo.private(`App.User.${this.user.id}`)
.notification((notification) => {
console.log(notification.type)
});
Response from my local environment (Successful)
Pusher : : ["Event sent",{"event":"pusher:subscribe","data":{"auth":"0d5290e189b56045e99d:e2156d7e13673a1e06f0c2b8974655247a55055de1f7eb31022a1a171615cb8c","channel":"private-App.User.4"}}]
broadcasting/auth response from local environment
Error from broadcasting/auth on heroku
Pusher : : ["Error: JSON returned from auth endpoint was invalid, yet status code was 200. Data was: "]
Error pusher broadcasting/auth
Any help or suggestions. Thanks
The auth endpoint response should be a JSON string with an auth property of a value composed from the application key and the authentication signature, separated by a colon : as follows:
{
"auth": "278d425bdf160c739803:58df8b0c36d6982b82c3ecf6b4662e34fe8c25bba48f5369f135bf843651c3a4"
}
You should check what the auth endpoint is returning.
Source

Laravel Echo not subscribing to private Channel

Echo Version: 1.8.0
Laravel Version: 7.0
PHP Version: 7.2.
NPM Version: 6.12.1
Node Version: 12.13.1
Description: I'm trying to send notifications to users,
My pusher connection is good because it sends on public channels
And also, i get this message on my console
[2020-07-24 21:08:09][355] Processed: Illuminate\Notifications\Events\BroadcastNotificationCreated
and on pusher i also see that the message was sent.
I also don't get any errors on my browser console as all the websocket connections are working well.
But i still dont get any messages.
I tried
Echo.private('App.User.' +userId)
  .notification((notification) => {
  console.log(notification);
  });
I also tried
Echo.private('App.User.' + userId)
  .listen('.Illuminate\\Notifications\\Events\\BroadcastNotificationCreated', (e) => {
  console.log('Event Notification received ', e)
});
Now I turned on Pusher error logging and i got
app.js:42600 Pusher : : ["JSON returned from auth endpoint was invalid, yet status code was 200. Data was: <!DOCTYPE html>\r\n<html lang=\"en\">\r\n
I also followed many tutorials and the docs
All to no avail.
Steps To Reproduce:
Create a notification and declare both the toArray method and toBroadcast methods but echo fails to catch messages from pusher
I finally solved this issue myself
Steps
In my bootstrap.js file
window.Echo = new Echo({
broadcaster: "pusher",
key: "my key",
cluster: "eu",
encrypted: true,
authEndpoint: "api/broadcasting/auth",
auth: {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
},
});
Then in my routes/api.php file,
Route::middleware('auth:api')->post('broadcasting/auth', function (Request $request) {
$pusher = new Pusher\Pusher(
$app_key,
$app_secret,
$app_id
);
return $pusher->socket_auth($request->request->get('private-my-channel'),($request->request->get('socket_id'));
});
There is more info on this in the documentation,
I hope it helps someone someday

laravel-websockets connect to channles without laravel-echo

I have a websocket server implemented with laravel-websockets package which broadcasts data on some private channels. At the moment server does not support two-way communication. I want to make this public for anyone to be able to connect to this websocket by using an auth token. But I can't find anything helpful regarding this.
Currently I am using laravel-echo and pusher-js to connect from a separate app which works fine. But what if someone does not want to use these packages i.e. what would be the nodejs implementation to connect to this socket.
For reference here is my laravel-echo implementation to connect to this socket.
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: '{appkey}',
wsHost: '{sockethosturl}',
wsPort: 6001,
forceTLS: false,
authEndpoint: '{auth endpoint on socket server}',
disableStats: true,
auth: {
headers: {
'Auth-Token': '{ random auth token }',
}
}
});
And then I subscribe to channels using this
Echo.private('private-channel-1')
.listen('.update', (event) => {
console.log("Found event");
console.log(event);
});
Looking for a way to translate this into a socket-io or any other websocket client side library.

Resources