Laravel Echo Server can not be authenticated, got HTTP status 500 - node.js

I've installed both Laravel echo server and Laravel echo client.
Following is the laravel-echo-server.json configuration.
{
"authHost": "http://taxation.com",
"authEndpoint": "/broadcasting/auth",
"clients": [
{
"appId": "APP_ID",
"key": "someKey"
}
],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": "127.0.0.1",
"port": "3000",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": ""
}
The following script listens for channel events. It builds fine with npm run dev.
import Echo from 'laravel-echo'
let token = document.head.querySelector('meta[name="token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
window.Echo = new Echo({
broadcaster: 'socket.io',
host: '127.0.0.1:3000',
reconnectionAttempts: 5
});
window.Echo.join('checked-in-1')
.listen('.user.checked_in', (e) => {
console.log(e);
});
When trying to listen for any event on start laravel-echo-server command. It keeps throwing Client can not be authenticated, got HTTP status 500.
Note :
I really didn't find anything helpful on laravel-echo-serve nor on google.
Any help will be appreciated a lot.
Laravel V5.4
Thanks

Just getting the issue because of CSRF token. Didn't passed the token to the echo.
window.Echo = new Echo({
broadcaster: 'socket.io',
host: '127.0.0.1:3000',
reconnectionAttempts: 5,
csrfToken: token.content <--
});

Related

Strapi api not giving a response when registering user even though it was updated in the admin panel

I am using Strapi with postgres to register a new Strapi end user and I am using the following code to send a post request with the new user's credentials:
//...
try {
// encrypt the user password
const encryptedUserPassword = await bcrypt.hash(password, 10);
const response = await axios.post(
"http://localhost:1337/api/auth/local/register",
{
username,
email: email.toLowerCase(),
password: encryptedUserPassword,
}
);
} catch (err) {
console.log(err);
res.status(500).send({ message: ["Registration failed"], error: err });
}
// ...
The problem that I am facing is that whenever I send the post request, the data is being successfully updated in the Strapi admin panel and eventually in the postgres database but it is not returning a successful response and it continues to process until it throws an Axios error even though the data is updated in my Strapi admin panel.
This is the error that I received when I send the post request to register a new user:
{
"message": [
"Registration failed"
],
"error": {
"message": "Request failed with status code 400",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"User-Agent": "axios/0.27.2",
"Content-Length": 130
},
"method": "post",
"url": "http://localhost:1337/api/auth/local/register",
"data": "{\"username\":\"testuser04\",\"email\":\"testuser09#email.com\",\"password\":\"$2a$10$pqeADn.WL4BqHYpTonVl2.KYqoxtuJZyvdpgc659W90zmsu4Wo2jW\"}"
},
"code": "ERR_BAD_REQUEST",
"status": 400
}
}
I am using the recommended Strapi node version 14.19.3 with the following package.json dependencies:
"devDependencies": {},
"dependencies": {
"#strapi/strapi": "4.2.3",
"#strapi/plugin-users-permissions": "4.2.3",
"#strapi/plugin-i18n": "4.2.3",
"pg": "8.6.0"
},
Could someone please help me or give me some tips on what I am doing wrong? Thank you in advance
Well, I just resolved this problem. It turns out that just needed to set the default value for the email confirmation in the admin panel to false. Also, I needed to authorize my application to make requests directly to the API

How to create JSON nested Objects using NodeJS and JSON.stringify()

My problem is in the port_password.
{
"server": "0.0.0.0",
"server_ipv6": "::",
"local_address": "127.0.0.1",
"local_port": 1080,
"timeout": 120,
"method": "aes-256-cfb",
"protocol": "origin",
"protocol_param": "",
"obfs": "tls1.2_ticket_auth",
"obfs_param": "",
"redirect": "",
"dns_ipv6": false,
"fast_open": true,
"workers": 1,
"port_password": "{\"10000\":\"pass\",\"10001\":\"pass\",\"10002\":\"pass\",}"
}
The code I used to generate JSON.
account.forEach(ssr => {
portsPasswords += JSON.stringify(ssr.port.toString()) + ':' + JSON.stringify(ssr.password.toString()) + ','
})
I want the output something like this. How can I achieve that using NodeJS and JSON.stringfy()?
{
"server": "0.0.0.0",
"server_ipv6": "::",
"local_address": "127.0.0.1",
"local_port": 1080,
"timeout": 120,
"method": "aes-256-cfb",
"protocol": "origin",
"protocol_param": "",
"obfs": "tls1.2_ticket_auth",
"obfs_param": "",
"redirect": "",
"dns_ipv6": false,
"fast_open": true,
"workers": 1,
"port_password": {
"10000":"pass",
"10001":"pass",
"10002":"pass"
}
}
reduce into an object instead:
const account = [
{ port: 10000, password: 'pass1' },
{ port: 10001, password: 'pass2' },
{ port: 10002, password: 'pass3' }
];
const port_password = account.reduce((a, { port, password }) => {
a[port] = password;
return a;
}, {});
const entireObj = {
"server": "0.0.0.0",
// etc
port_password
};
console.log(JSON.stringify(entireObj));

Laravel Echo with NodeJS HTTPS doesn't work

I've been developing this NodeJS application that takes advantage of Laravel Echo's functionalities to receive information from a server through socket connection.
Server-side
Laravel Echo Server with Laravel 5.7.19
Client-side
"laravel-echo": "^1.5.2"
"socket.io": "^2.2.0"
import Echo from '../../node_modules/laravel-echo/dist/echo.common.js'
import Socketio from 'socket.io-client';
let echo = new Echo({
broadcaster: 'socket.io',
host: 'https://smartfish.danymota.com:8080/',
encrypted: true,
secure: true,
client: Socketio,
auth: {
headers: {
'Authorization': 'Bearer ' + this.token.bearerToken,
},
},
});
echo.private('central.' + macAddress)
.listen('RulesUpdated', (response) => {
handleRules(JSON.parse(response.aquarios))
console.log(new Date().toLocaleString() + " - Rules updated")
})
Problem
Everything works fine in Http, when I switch to HTTPS it just stops working. Also, the socket connection doesn't reach the server (or at least Laravel-echo-server doesn't log it)
IMPORTANT - What I've tried
Ran the application through Browserify, and then on the browser (it works just fine on a browser, even with HTTPS)
Played around with different ports (Again, it works with HTTP, so ports are likely not the problem)
Changed the URL to wss://, /socket.io
Forced socket.io to include a secure: true on options
Changed the version of Laravel Echo
Tried importing both echo.common.js and echo.js
Notes
/api/broadcasting/auth - This is working, so problem is likely not here
Laravel echo server configuration
{
"authHost": "https://smartfish.danymota.com",
"authEndpoint": "/api/broadcasting/auth",
"clients": [{
"appId": "f7506b5e7118092c",
"key": "9015d93999f3a2f7f95a054a76fbcbfd"
}],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath1": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "8080",
"protocol": "https",
"socketio": {},
"sslCertPath": "/home/danymota/ssl/cert/smartfish.danymota.com.crt",
"sslKeyPath": "/home/danymota/ssl/private/smartfish.danymota.com.key",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": true,
"allowOrigin": "http://smartfishweb.test/api",
"allowMethods": "GET, POST",
"allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}
}
Socket.io debug
socket.io-client:url parse https://smartfish.danymota.com:8080/socket.io +0ms
socket.io-client new io instance for https://smartfish.danymota.com:8080/socket.io +0ms
socket.io-client:manager readyState closed +0ms
socket.io-client:manager opening https://smartfish.danymota.com:8080/socket.io +0ms
socket.io-client:manager connect attempt will timeout after 20000 +4ms
socket.io-client:manager readyState opening +1ms
socket.io-client:manager connect_error +60ms
socket.io-client:manager cleanup +0ms
Thank you all in advance.
that because you have to set laravel echo server settings
use this command laravel-echo-server init and choose https when setting the protocol
or open laravel-echo-server.json
and change protocol to https
{
"authHost": "https://smartfish.danymota.com:8080",
"authEndpoint": "/broadcasting/auth",
"clients": [
{
"appId": "It generates it from the command init",
"key": "It generates it from the command init"
}
],
"database": "Your database driver",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "6001", // your node js port the default is 6001
"protocol": "https", // change it here
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"apiOriginAllow": {
"allowCors": true,
"allowOrigin": "Your domain with the port",
"allowMethods": "GET, POST",
"allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}
}
I've solved this problem by adding a flag rejectUnauthorized: false to laravel echo.
this.echo = new Echo({
broadcaster: 'socket.io',
host: config.ECHO_SERVER,
client: Socketio,
rejectUnauthorized: false,
auth: {
headers: {
'Authorization': 'Bearer ' + this.token.bearerToken,
},
},
})

Can't make serverside axios api call behind a firewall

I'm looking into axios to use for some node.js http calls to APIs while inside a corp firewall - and i'm falling down at the first hurdle.
I found an example that uses axios to do a server http call below
const axios = require('axios');
const API = 'https://jsonplaceholder.typicode.com';
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
// Get all posts
router.get('/posts', (req, res) => {
// Get posts from the mock api
axios.get(`${API}/posts`, { proxy: { host: 'http://proxy.com', port: 8080}})
//axios.get(`${API}/posts`)
.then(posts => {
res.status(200).json(posts.data);
})
.catch(error => {
res.status(500).send(error)
});
});
module.exports = router;
but when i'm behind the firewall i get an error below
// http://localhost:3000/api/posts
{
"code": "ENOTFOUND",
"errno": "ENOTFOUND",
"syscall": "getaddrinfo",
"hostname": "http://proxy.com",
"host": "http://proxy.com",
"port": 8080,
"config": {
"transformRequest": {
},
"transformResponse": {
},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"User-Agent": "axios/0.15.3",
"host": "jsonplaceholder.typicode.com"
},
"method": "get",
"proxy": {
"host": "http://proxy.com",
"port": 8080
},
"url": "https://jsonplaceholder.typicode.com/posts"
it works find when i switch to a direct connection to the internet and the proxy setting are what i use for npm - i'm not sure if the final solution will be inside or outside of the firewall but i can't figure out to do this either specific to this api or even globally just for dev.. any help would be appreciated..
I believe that axios just wants the host in the proxy config, not the URL with protocol:
"proxy": {
"host": "proxy.com",
"port": 8080
}

tedious.js set requestTimeout = 0 but still got timed out

I have this config file:
{
"userName": "user",
"password": "pass",
"server": "shrd-cw",
"options": {
"encrypt": true,
"requestTimeout": 0
}
}
However, I still received requestTimeout error:
{ [RequestError: Timeout: Request failed to complete in 15000ms]
name: 'RequestError',
message: 'Timeout: Request failed to complete in 15000ms',
code: 'ETIMEOUT' }

Resources