簡體   English   中英

在為 Node.JS 編寫的非常低級別的 TCP 服務器上進行身份驗證?

[英]Authentication on a very low level TCP Server written for Node.JS?

如何在為 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 服務器和 email 客戶端提供的行):

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

或您要支持的任何其他命令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM