如何在龙卷风websocket处理程序中拒绝websocket握手

时间:2019-05-31 13:28:38

标签: python websocket tornado handshake

因此,我正在对我编写的具有websocketHandler的龙卷风服务器进行单元测试。这是我的测试代码:

def test_unauthorized_websocket(self):
    message = "Hey bro"     
    ws = websocket.create_connection('ws://localhost:8888/ws', header=['Authorization: false'])
    send_dict = {'command': test_command, 'message': message}
    serialized_dict = json.dumps(send_dict)
    ws.send(serialized_dict)
    response = ws.recv()
    #test response with assert

此测试的目的是证明我的龙卷风服务器正确地拒绝并关闭了该Websocket连接,因为身份验证标头错误。 这是我的龙卷风websocketHandler代码:

class WebSocketHandler(tornado.websocket.WebSocketHandler):

   def open(self):
      #some code
      headers = self.request.headers
      try:
          auth = headers['Authorization']
      except KeyError:
          self.close(code = 1002, reason = "Unauthorized websocket")
          print("IT'S CLOSED")
          return

       if auth == "true":
          print("Authorized Websocket!")
          #some code
       else:
          print("Unauthorized Websocket... :-(")
          self.close(code = 1002, reason = "Unauthorized websocket")

因此,当验证错误时,将调用self.close()(不确定我是否需要代码和理由)。这将关闭websocket。但这实际上并没有发生在“客户端”端。在“客户端”中调用create_connection()后,ws.connected变量仍然为True,而当我执行ws.send()时,仍会调用on_message的{​​{1}}方法当尝试使用websocketHandler做出响应时,它会引发self.write_message()。然后,“客户端”才真正关闭websocket的一侧,WebSocketClosedError不返回任何内容,然后ws.recv()变为False。 我有什么方法可以(通过握手标头或其他方式)与客户端通信,表明websocket应该在其一侧更早关闭?

1 个答案:

答案 0 :(得分:0)

您可以覆盖prepare()并引发tornado.web.HTTPError,而不是覆盖open()并调用self.close()。这将首先拒绝连接,并且将在客户端将其报告为create_connection()的一部分,而不是在以后的阅读中进行报告。