Autobahn | Python Twisted服务器,检查API密钥并断开客户端连接

2024-09-29 20:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想添加一个简单的API密钥检查到一个autobahnpythonwebsocket服务器。服务器应该检查客户机HTTP报头中的密钥,并断开没有正确密钥的客户端。在

我已经想出了一个解决办法,但我不确定这是最好的解决办法(见下文)。如果有人有建议,我会很感激的。在


Tags: 服务器apihttp客户端客户机密钥建议我会
2条回答

从onConnect方法的API Docs中:

Throw autobahn.websocket.types.ConnectionDeny when you don’t want to accept the WebSocket connection request.

您可以在示例之一here的第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中的连接,我会得到一个错误消息:我无法关闭尚未连接的连接。上面的解决方案在客户端关闭得很干净,但是在服务器端的行为却很奇怪。日志输出是

^{pr2}$

服务器端关闭消息为“无”的原因是服务器关闭了连接而客户端没有发回吗?有更好的方法吗?在

更新: 我接受了亨利·希思的答案,因为它似乎是官方支持的解决方案,尽管它并不能彻底地关闭连接。使用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头可以通过请求.headers而在onOpen中,它们可以通过self.http_头文件. 在

相关问题 更多 >

    热门问题