Using Nodejs to create a websocket service is very simple ("WS" Module, etc.) and there are many online tutorials. The WebSocket service does not have connection validation by default, plus it supports cross-domain connections, so there is a risk of "stealing" and concurrent attacks.
Nodejs's "WS" Module provides a Verifyclient callback method that can obtain connection information such as URLs when the client connects. This allows us to add our own authentication information (user name, password, etc.) to the connection URL. Directly on the code:
************************************************************
Back end: Myws.js
var util = require (' util ');
var url = require (' URL ');
var server = require (' ws '). Server;
var wss = new Server ({port:8181, verifyclient:clientverify});
Wss.on (' Connection ', function (WS) {
Console.log (' client connected ');
Ws.on (' message ', function (message) {
Ws.send ("message received!");
});
Ws.on (' Close ', function (Close) {
Console.log ("client closed");
});
});
Validation functions
function Clientverify (info) {
var ret = false;//Reject
var params = Url.parse (Info.req.url, true). Query;
if (params["id"] = = "Luoc83" && params["key"] = = "123456") {
ret = true;//Through
}
return ret;
}
************************************************************
Front End: myws.htm
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<script type= "Text/javascript" language= "JavaScript" >
var ws;
var user = "Luoc83";
var psw= "12345";//now is the wrong password, the correct is "123456"
function Connect () {
WS = New WebSocket ("ws://localhost:8181?id=" +user+ "&key=" +PSW);
Ws.onopen = function (e) {
Alert ("Connect success");
}
Ws.onclose = function () {
Alert ("Close");
}
Ws.onerror = function (e) {
Alert ("Connect error!");
};
Ws.onmessage = function (event) {
alert (event.data);
};
}
</script>
<body >
<button onclick= "Connect ()" > Test </button>
</body>
************************************************************
Test steps:
1) Start back-end service: node Myws.js
2) in the browser open myws.htm, click on the "Test button", pop-up prompt: "Connect error!" and "close"
Press "F12" to see the prompt message:
WebSocket connection to ' ws://localhost:8181/?id=luoc831&key=123456 ' failed:http authentication failed; No valid credentials available
The description is clear: Validation failed
3) Modify myws.htm var psw= "12345" for var psw= "123456", save, open in the browser, click on the "Test button", pop up the hint "connect success", indicating the success of the verification.
Create a WebSocket service that joins user authentication using Nodejs