![](/img/trans.png)
[英]Autobahn Twisted websocket server and Swagger server multithreaded in python?
[英]Autobahn|Python Twisted server that checks API key and disconnects clients
我想向Autobahn Python WebSocket服務器添加一個簡單的API密鑰檢查。 服務器應檢查客戶端HTTP標頭中的密鑰,並斷開沒有正確密鑰的客戶端。
我已經找到了解決方案,但是我不確定這是最好的解決方案(見下文)。 如果有人提出建議,我將不勝感激。
我的解決方案是在客戶端連接到服務器后檢查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.