高速公路|Python 扭曲服务器,用于检查 API 密钥并断开客户端连接



我想向Autobahn Python WebSocket服务器添加一个简单的API密钥检查。服务器应检查客户端的 HTTP 标头中的密钥,并断开没有正确密钥的客户端的连接。

我已经找到了解决方案,但我不确定这是最好的解决方案(见下文)。如果有人有建议,我将不胜感激。

来自 onConnect 方法的 API 文档:

当您不想接受 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

服务器端关闭消息的原因是 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访问它们。

最新更新