Search code examples
node.jssocket.ioipwhitelist

How to set an IP whitelist on a NodeJS socket.io server?


I'd like to restrict the connection to the socket server only to a list of IP, is there any simple way to do that? I couldn't find any so far.

Thanks


Solution

  • Following @proxim0 post, I used a middleware :

    io.use((socket, next) => {
        fs.readFile(__dirname + '/config.json', function(err, file) {
            if(err) return next(new Error("Internal error : " + err.message));
    
            const config = JSON.parse(file.toString('utf8'));
            if(!config.restrictAccess) return next();
            
            var ip = socket.request.headers['x-forwarded-for'] || socket.request.socket.remoteAddress || null;
    
            if(ip == null || config.allowedAddresses.indexOf(ip) == -1) {
                console.log("Access denied from remote IP " + ip);
                return next(new Error("Your IP address is not allowed to access this resource."));
            }
            next();
        });
    });
    

    With a config.json file with the following format :

    {
        "restrictAccess": true,
        "allowedAddresses": [
            "127.0.0.1",
            "123.456.789"
        ]
    }
    

    Any comment on improvment is welcome.