Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Https Nginx NodeJS SocketIO And CORS request failed

Here is my problem,

Context :

I have a NGinx server working. NGinx uses a certificate to enable HTTPS. No problem from there.

I have a NodeJS server working, which is just supposed to handle websockets, using socketIO.

I am testing on Mozilla Firefox (which is maybe not the best thing...)

App was first on HTTP, and everything was working fine. Now that all switched to HTTPS, I face a "cross-origin" issue.

I already tried several solutions, but none of them worked for me yet... I will explain what I tried at the end of the post.

First, let me show you the concerned files, server.js for nodeJS, nginx.conf for NGinx server, and "client script" which is supposed to connect the websocket.

server.js - NodeJS

var app = require('express')();
var fs = require('fs');
var https = require('https');
var _ = require('underscore');
var socketio = require('socket.io');
var options = {
    key: fs.readFileSync('/ssl/file.key'),
    cert: fs.readFileSync('/ssl/file.crt')
};
var server = https.createServer(options).listen(9001,function(){
    console.log("SERVER LISTENING");
});
io = socketio.listen(server,{origins:'*:*'});

var connectedSockets = {};

_.each(io.nsps, function(nsp){
  nsp.on('connect', function(socket){
    if (!socket.auth) {
      delete nsp.connected[socket.id];
    }
  });
});

function checkAuthToken(token,callback){
    callback(null,true);
}

io.on('connection',function(socket){
    socket.broadcast.emit('hi');
    socket.on('disconnect',function(){
        console.log('a user disconnected');
    });
    socket.on('chat message',function(msg){
        io.emit('chat message',msg);
    });
    socket.on('authenticate', function(data){
      checkAuthToken(data.token, function(err, success){
        if (!err && success){
          socket.auth = true;
          _.each(io.nsps, function(nsp) {
            if(_.findWhere(nsp.sockets, {id: socket.id})) {
              nsp.connected[socket.id] = socket;
            }
          });
        }
      });
    });
});

It is a "simple" chat application, several things need to be completed such as the script that is supposed to check authentification...

nginx.conf - NGinx Server Config

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    map $http_upgrade $connection_upgragde {
        default upgrade;
        '' close;
    }
    sendfile        on;
    server {
        listen 80;
        server_name 192.168.100.22;
        rewrite ^ https://$http_host$request_uri? permanent;
    }
    server {
        listen       443;
        ssl on;
        ssl_certificate /ssl/file.crt;
        ssl_certificate_key /ssl/file.key;
        server_name  192.168.100.22;
        root E:/www;
        index index.php index.html index.htm;
        add_header Access-Control-Allow-Origin *;
        add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
        proxy_set_header X-Forwarded-For $remote_addr;
        server_tokens off;
        charset utf-8;
        error_page   500 502 503 504  /50x.html;
        location ~ \.php$ {
            try_files $uri =404;
            include /Nginx/nginx-1.8.0/conf/fastcgi_params;
            fastcgi_param HTTPS on;
            fastcgi_param HTTP_SCHEME https;
            fastcgi_split_path_info ^(.+\.php)(.*)$;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
    }
}

Client.js - Connection script in index.php

<script src="./jquery-1.11.1.js"></script>
<script src="./socket.io-1.3.5.js"></script>
<script>
  var socket = io('wss://192.168.100.22:9001');
  $("form").submit(function(){
    socket.emit('chat message',$('#m').val());
    $('#m').val('');
    return false;
  });
  socket.on('connect', function(){
      socket.emit('authenticate', {token: 456456456,rights:'any'});
    });
  socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });
  socket.on('hi',function(){
    $('#messages').append($('<li>').text('connection'));
  });
</script>

The server is located on 192.168.100.22 IP

Nginx listens 80 & 443 and redirects all traffic to 443 (https)

Access to folders through nginx is ok, the current chat test is located at 192.168.100.22/websocks/index.php

Error message is the following :

GET https://192.168.100.22:9001/socket.io/?EIO=3&transport=polling&t=1432131062725-0 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://192.168.100.22:9001/socket.io/?EIO=3&transport=polling&t=1432131062725-0. Reason: CORS request failed

Actually, I already tried to add this to the nodejs script :

https.globalAgent.options.rejectUnauthorized = false;
app.get('*',function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Headers","X-Requested-With");
    next();
});

But Nothing worked yet...

Thanks for reading / help

like image 601
Julo0sS Avatar asked Nov 10 '22 13:11

Julo0sS


1 Answers

Verify that your SSL certificate is valid and name matches your domain. It looks like you are using the IP address instead of the domain name of the certificate. I've seen the CORS error when Firefox was complaining about the certificate.

like image 132
Kenan Avatar answered Nov 14 '22 21:11

Kenan