WEB套接字的CORS验证 [英] CORS validation for WEB Socket

查看:88
本文介绍了WEB套接字的CORS验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用expressjs并为所有来源添加了cors验证。

  const options = {


来源:['*'],
凭据:true,
暴露标头:false,
飞行前继续:false,
选项成功状态:204,
方法:['GET','POST'],
allowedHeaders:allowedHeaders,
};

module.exports = cors(options);

这将启用我正在使用的两个CORS请求之一,其中之一是来自服务器的响应,另一个是套接字。



我正在使用可观察的角度来获得响应。

  const headers = {
//主机:’’,
};
返回this.http.get(`$ {environment.BASE_URL}:$ {_ port}`,
{标头,观察:响应});
}

不是套接字的请求会发送适当的响应。但是,带有插座的那个向我发送了另一个对象。



但是,如果我查看网络标签,也会从套接字获得正确的响应。



请参见下面的截图。



(网络标签中的响应标题)





如果我在Firefox浏览器上打开CORSe扩展名,则可以获取此标头。



编辑:
我不使用Socket.io,而是使用Web套接字 websocket = require('ws');






ANSWER :我的问题是一个逻辑错误。



这并不是解决我问题的确切方法,因为我使用的是websocket而不是socket.io,但是,这使我意识到了我的问题,我在听websocket和https另外,一旦我添加了在websocket中使用cors的选项,便能够解决此问题。

解决方案

我的示例在起作用,套接字

  // socket.js服务器配置,用于express 

const app = express( );
const server = app.listen(process.env.SOCKET_PORT,function(){
console.log(服务器已启动:http:// localhost: + process.env.SOCKET_PORT + / );
});

app.use(函数(req,res,next){
res.setHeader(
Access-Control-Allow-Headers,
X- Access-Token,Content-Type,Lang,crossDomain
);
res.setHeader(
Access-Control-Allow-Methods,
POST,GET,OPTIONS ,PUT,DELETE
);
res.setHeader( Access-Control-Allow-Origin, *);
req.headers.host = req.headers [ x -forwarded-host];
res.setHeader( Cache-Control, no-cache);

//拦截OPTIONS方法
if('OPTIONS' === req.method){
//回应200
res.sendStatus(200);
} else {
//继续
next() ;
}
});

const io = require('socket.io')(服务器,{
传输方式:[
//'polling',
websocket
],
allowUpgrades:true,
适配器:redisAdapter({host:'localhost',port:process.env.REDIS_PORT ||'6379'}),
pingInterval:3000,
wsEngine:'ws'
})

我也有在nginx.conf中配置

 位置/ {
//重要行

proxy_set_header' Access-Control-Allow-Origin''*';
proxy_set_header访问控制允许方法 GET,POST,OPTIONS;

#将所有流量重定向到本地端口;
proxy_set_header主机$ http_host;
proxy_set_header X-Real-IP $ remote_addr;
proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_set_header X-Forwarded-Proto $ scheme;

proxy_redirect关闭;
proxy_read_timeout 86400;

#防止502错误的网关错误
proxy_buffers 8 32k;
proxy_buffer_size 64k;

reset_timedout_connection开启;


//您的端口在这里
proxy_pass http:// localhost:YOUR_PORT;
proxy_http_version 1.1;
proxy_set_header升级$ http_upgrade;
proxy_set_header连接升级;
proxy_set_header主机$ host;
proxy_cache_bypass $ http_upgrade;
}



I'm using expressjs and added cors validation for a all origins.

const options = {


 origin: ['*'],
  credentials: true,
  exposedHeaders: false,
  preflightContinue: false,
  optionsSuccessStatus: 204,
  methods: ['GET', 'POST'],
  allowedHeaders: allowedHeaders,
};

module.exports = cors(options);

This is enabling one of the two CORS requests that I'm using however, One of which is a response from server and the other one is a socket.

I'm using angular observable to get the response like.

    const headers = {
      // Host: '',
    };
    return this.http.get(`${environment.BASE_URL}:${_port}`,
 { headers, observe: 'response' });
  }

The request that is not a socket sends a proper response. However, the one with the socket is sending me a different object.

But I'm also getting the right response from socket if I look into the network tab.

See screenshots below.

https://prnt.sc/qlq9up (CORS Invalid)

https://prnt.sc/qlqd88 (Response Header in network Tab)

This header is retrievable if I turn on the CORSe Extension on my Firefox Browser.

EDIT: I'm not using Socket.io but rather a Web Socket websocket = require('ws');


ANSWER : My issue was a logical error.

This wasn't exactly what solved my issue because I was using websocket and not socket.io however, this made me realize my problem, I was listening to websocket and https seperately and was able to fix this once I added the option to use cors in websocket

解决方案

my example that is working, socket are to different server

// socket.js server config,for express

const app = express();
const server = app.listen(process.env.SOCKET_PORT, function () {
    console.log("Server started: http://localhost:" + process.env.SOCKET_PORT + "/");
});

app.use(function (req, res, next) {
    res.setHeader(
        "Access-Control-Allow-Headers",
        "X-Access-Token, Content-Type, Lang, crossDomain"
    );
    res.setHeader(
        "Access-Control-Allow-Methods",
        "POST, GET, OPTIONS, PUT, DELETE"
    );
    res.setHeader("Access-Control-Allow-Origin", "*");
    req.headers.host = req.headers["x-forwarded-host"];
    res.setHeader("Cache-Control", "no-cache");

    //intercepts OPTIONS method
    if ('OPTIONS' === req.method) {
        //respond with 200
        res.sendStatus(200);
    } else {
        //move on
        next();
    }
});

const io = require('socket.io')(server, {
    transports: [
        // 'polling',
        "websocket"
    ],
    allowUpgrades: true,
    adapter: redisAdapter({host: 'localhost', port: process.env.REDIS_PORT || '6379'}),
    pingInterval: 3000,
    wsEngine: 'ws'
})

also I have config inside nginx.conf

 location / {
// important line

        proxy_set_header 'Access-Control-Allow-Origin' '*';
        proxy_set_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

  # redirect all traffic to local port;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_redirect off;
        proxy_read_timeout 86400;

        # prevents 502 bad gateway error
        proxy_buffers 8 32k;
        proxy_buffer_size 64k;

        reset_timedout_connection on;


//your port here
        proxy_pass http://localhost:YOUR_PORT;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }


这篇关于WEB套接字的CORS验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆