I'd like to implement http basic auth authentication into my nodejs websocket app. Here's my piece of code:
var http = require('http');
var auth = require('http-auth');
var express = require('express');
var app = express();
//....
basic = auth.basic({
realm: "websocket auth",
file: __dirname + "/users.htpasswd"
});
var server = http.createServer(basic);
app.listen = function() {
return server.listen.apply(server, arguments);
};
// WEBSOCKET
var WebSocketServer = require('websocket').server;
var wss = new WebSocketServer({
httpServer: server
});
wss.on('request', function(request) {
var connection = request.accept();
connection.sendUTF('Server: message ws auth');
});
For standard http access authentication it works fine, but I can't get it working on websocket, when I connect through websocket I immediately get response. Is it even possible to authenticate via http on websocket?
Not directly.
Websockets aren't HTTP so they don't do things like HTTP AUTH, send cookies, etc.
For our websocket connections we pass in the cookie as a parameter on the request URL. We are using socket.io, however, which has a provision for setting an authentication function sort of similar to an HTTP server's middleware.
You should be able to do something similar with the #accept method from Websocket-node. Examine the data coming in and if it's not authorized, reject the connection.