簡體   English   中英

Autobahn | Python Twisted服務器,用於檢查API密鑰並斷開客戶端連接

[英]Autobahn|Python Twisted server that checks API key and disconnects clients

我想向Autobahn Python WebSocket服務器添加一個簡單的API密鑰檢查。 服務器應檢查客戶端HTTP標頭中的密鑰,並斷開沒有正確密鑰的客戶端。

我已經找到了解決方案,但是我不確定這是最好的解決方案(見下文)。 如果有人提出建議,我將不勝感激。

API文檔中的onConnect方法:

當您不想接受WebSocket連接請求時,拋出autobahn.websocket.types.ConnectionDeny。

你可以看到的例子之一的117線完成這件事在這里

我已經對此進行了測試,它不能干凈地關閉連接。 但是,您將終止與未經身份驗證的客戶端的連接,因此您不希望進行關閉握手。

onClose回調函數使用wasClean參數,該參數可讓您區分干凈連接和不干凈連接的關閉。

我的解決方案是在客戶端連接到服務器后檢查HTTP標頭,如果客戶端沒有有效的API密鑰,則關閉連接。

MY_API_KEY = u'12345'

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {}".format(request.peer))

    def onOpen(self):
        # Check API Key
        if 'my-api-key' not in self.http_headers or\
            self.http_headers['my-api-key'] != MY_API_KEY:
            # Disconnect the client
            print('Missing/Invalid Key')
            self.sendClose( 4000, u'Missing/Invalid Key')

        # Register client
        self.factory.register(self)

我發現如果關閉onConnect內的連接,則會收到一條錯誤消息,提示我無法關閉尚未連接的連接。 上面的解決方案在客戶端完全關閉,但在服務器端卻表現異常。 日志輸出為

dropping connection: None
Connection to/from tcp4:127.0.0.1:51967 was aborted locally
_connectionLost: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionAborted'>: Connection was aborted locally, using.
    ]
WebSocket connection closed: None

服務器關閉消息為“無”的原因是服務器關閉了連接並且客戶端沒有發回郵件嗎? 有一個更好的方法嗎?

更新:我接受了亨利·希思的回答,因為它似乎是官方支持的解決方案,即使它不能干凈地關閉連接。 使用autobahn.websocket.types.ConnectionDeny ,解決方案變為

from autobahn.websocket.types import ConnectionDeny
MY_API_KEY = u'12345'

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {}".format(request.peer))
        # Check API Key
        if 'my-api-key' not in request.headers or\
            request.headers['my-api-key'] != MY_API_KEY:
            # Disconnect the client
            print('Missing/Invalid Key')
            raise ConnectionDeny( 4000, u'Missing/Invalid Key')

    def onOpen(self):
        # Register client
        self.factory.register(self)

請注意,在onConnect中,HTTP標頭可通過request.headers訪問,而在onOpen中,它們可通過self.http_headers訪問。

暫無
暫無

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

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