Socket.io + HaProxy + HTTP Authentication
Bistri Team
December 16, 2011
engineering
We wanted to add an authentication step before accessing static and socket.io served by node.js. But stock port redirections do not work.
Because websockets breaks HTTP 1.1 protocol, Nginx was unable to complete the task. So we used HAProxy with his tcp mode and a small test to identify and redirect websocket connections.
# /etc/haproxy/haproxy.cfg (snippet) # ACL & Auth for connect and socket.io front end userlist UsersAuth group admin users admin user admin insecure-password mypassword # Setup the listenning port frontend all 0.0.0.0:80 timeout client 86400000 default_backend www_papou acl is_websocket hdr(Upgrade) -i WebSocket use_backend socket_backend if is_websocket # web partbackendbackend www_papou balance roundrobin option forwardfor # This sets X-Forwarded-For option httplog timeout server 30000 timeout connect 40000 # restrict to authenticated users acl AuthOkay_Web http_auth(UsersAuth) http-request auth realm AuthYourself if !AuthOkay_Web # forward to the real server server server1 localhost:8000 weight 1 maxconn 1024 check # socket.io part backend socket_backend balance roundrobin option tcplog timeout queue 5000 timeout server 86400000 timeout connect 86400000 server socket localhost:8000 weight 1 maxconn 1024 check #end config
With this setup, incomming connections on port 80 are proxy-ied to port 8000 on the node.js app and anonymous access is prohibited and delegated to the proxy.
So far, it works well using websocket transport. Indeed firewalling must be set up to prevent direct connections to port 8000.
Versions used : nodejs 0.4.10, haproxy 1.4.8 , socket.io 0.8.7