在为Node.JS编写的非常低级的TCP服务器上进行身份验证?

| 如何在为Node.JS编写的TCP服务器中实现类似于HTTP基本身份验证的功能?基本的TCP服务器的代码如下:
// Load the net module to create a tcp server.
var net = require(\'net\');

// Setup a tcp server
var server = net.createServer(function (socket) {

  // Every time someone connects, tell them hello and then close the connection.
  socket.addListener(\"connect\", function () {
    console.log(\"Connection from \" + socket.remoteAddress);
    socket.end(\"Hello World\\n\");
  });

});

// Fire up the server bound to port 7000 on localhost
server.listen(7000, \"localhost\");

// Put a friendly message on the terminal
console.log(\"TCP server listening on port 7000 at localhost.\");
    
已邀请:
虽然有几种方法可以通过TCP连接提供身份验证,但是所有方法都需要某种形式的“协议”作为一种公认的通信语法/语法。 例如,在“简单邮件传输协议”中,发生以下对话(其中S:和C:分别表示SMTP服务器和电子邮件客户端提供的行):
S: 220 server.example.com
C: HELO client.example.com
S: 250 server.example.com
C: MAIL FROM:<sender@example.com>
S: 250 2.1.0 sender@example.com... Sender ok
C: RCPT TO:<recipient@example.com>
S: 250 recipient <recipient@example.com> OK
C: DATA
S: 354 enter mail, end with line containing only \".\"
C: full email message appears here, where any line
C: containing a single period is sent as two periods
C: to differentiate it from the \"end of message\" marker
C: .
S: 250 message sent
C: QUIT
S: 221 goodbye
在来自服务器的答复中,初始数值指示所请求操作的成功或失败,或者该答复包含参考消息。使用三位数字值可进行有效的解析,因为所有以2xx开头的答复都表示成功,以3xx表示信息性答复,以4xx表示协议错误,并且为服务器错误保留了5xx。有关完整协议,请参见IETF RFC 5321-http://tools.ietf.org/html/rfc5321。 因此,在您的特定情况下,您可以考虑以下简单内容:
[connect to TCP server]
S: ?                    # indicates the server is ready for authorization

C: username password   # send authentication credentials
然后,服务器将回复:
S: !                    # indicates successful authentication and 
                        # that server is ready for more commands 
要么
S: ?                    # indicates authentication failure
如果看到太多的身份验证失败尝试,则服务器可能会切断连接以减少滥用的可能性,例如DDOS攻击。 身份验证后,客户端可以发送:
C: >                    # begin streaming
或您要支持的任何其他命令。     

要回复问题请先登录注册