Ahmed Zain Salem
Ahmed Zain Salem

Reputation: 47

Node.js WebSocket setup returns 407 and 403 errors on a Red Hat server

I'm trying to implement WebSocket functionality in Node.js on a Red Hat server, but I keep running into issues with HTTP status codes. Initially, my code returned a 407 Proxy Authentication Required error, so I attempted a few changes, but now it's giving me a 403 Forbidden error instead.

Here's my current code:

require("dotenv").config({ path: '.env' });
const Request = require("request");
const WebSocket = require("ws");
const https = require('http');
const sql = require("mssql");

const server = https.createServer((req, res) => {
    console.log('Server is running and received a request!');
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('ijtimaati ...!\n')
});

const websocet = new WebSocket.Server({ server });

var action = "events";
var user = {};
var payload = [];
var rooms = {};

websocet.on("connection", (ws, request) => {
    let req = new URLSearchParams(request.url.replace("/?", "?").substring(1));
    let token = req.get("token");
    let document = req.get("document");
    let ref = req.get("ref_id");

    if (!(document && token && ref)) {
        ws.close(1000, "Please provide a valid token and document");
        return;
    }

    if (!req.get("endpoint")) {
        ws.close(1000, "Please provide a valid API endpoint");
        return;
    }
    
    let httpRequest = {
        rejectUnauthorized: false,
        headers: {
            "Content-type": "application/json",
            "Accept": "application/json",
            "token": token
        },
        url: "http://" + req.get("endpoint") + "/public/index.php/api/library/check/" + document
    };

    Request(httpRequest, (error, response, body) => {
        console.log(response.statusCode);
    });
});

To address the 407 error, I modified the setup by introducing HTTPS:

const https = require('https');
const httpsOptions = {
    key: fs.readFileSync('path/to/key.pem'),
    cert: fs.readFileSync('path/to/cert.pem')
};

const httpsServer = https.createServer(httpsOptions, (req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, World! (HTTPS)\n');
});

With this change, the 407 error disappeared, but now I receive a 403 Forbidden error instead.

Questions:

  1. Why did switching to HTTPS change the error from 407 to 403?
    2.Is there a specific configuration required for WebSocket connections over HTTPS on a Red Hat server?

Any insights or solutions would be greatly appreciated. Thank you!

Upvotes: 0

Views: 29

Answers (0)

Related Questions