Node.js + Socket.io | Set custom headers on the se

2019-05-23 03:57发布

I use Helmet with Express to set quite some security HTTP headers from the server side. This is nicely done, when rendering client pages on top of the node.js app, using:

var app = express();
app.use(helmet());
..
res.render("pages/index", data);

All the resources on the index page will have the Helmet headers. Unfortunately, socket.io does its own header management. So, anything that comes after /socket.io/ will have insecure/its own headers. For example here:

<https_path>/socket.io/socket.io.js
<https_path>/socket.io/?EIO=3&transport=polling&t=Lj4CFnj&sid=ILskOFWbHUaU6grTAAAA

Hence, I want to set custom headers for all socket.io items manually.

This is how I require socket.io (excerpt only):

/src/app.js

var express = require("express");
var sio = require("socket.io");
var app = express();
var io = require("./../lib/io.js").initialize(app.listen(REST_PORT, () => {
    logger.info("Application ready on port " + REST_PORT + " . Environment: " + NODE_ENV);
}));

/lib/io.js

exports = module.exports = {};
var sio = require("socket.io");
exports.initialize = function(server) {
    var options = {
        cookie: false,
        extraHeaders: {
        "X-Custom-Header-For-My-Project": "Custom stuff",
        }
    };
    io = sio(server, options);
    io.on("connection", function(socket) {
    // logic
)};

The "extraHeaders" option doesn´t work, I guess it could only with socket.io-client. I did large amount of googling around, but not luck on this.

Also looked around how to use socket.request (apparently it helps with headers, according to: here), but I couldn´t figure that out either.

Could you guys help?

0条回答
登录 后发表回答