Python websocket通过基本身份验证自动关闭

时间:2019-04-23 14:43:54

标签: python python-3.x websocket basic-authentication

我正在尝试使用python 3.7使用websocket-client库设置websocket。 API提供程序的文档指出必须进行基本身份验证。

以下是我尝试订阅其测试频道的代码。测试通道应不间断地发送响应,直到我们关闭套接字为止。

email = b'myemail@domain.com'
pw = b'mypassword'
_str = (base64.b64encode(email + b':' + pw)).decode('ascii')
headerValue = 'Authorization: Basic {0}'.format(_str)

def on_message(ws, msg):
    global msg_received
    print("Message received:     ", msg)
    msg_received += 1
    if msg_received > 10:
        ws.send(json.dumps({"unsubscribe": "/test"}))
        ws.close()


def on_error(ws, error):
    print("ERROR:     ", error)


def on_close(ws):
    print("Closing websocket...")


def on_open(ws):
    print("Opening...")
    ws.send(json.dumps({'subscribe': '/test'}))
    time.sleep(1)


if __name__ == '__main__':
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://api-ws.myurl.com/",
                                header=[headerValue],
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close))
    ws.on_open = on_open
    ws.run_forever()

运行此命令时,我可以看到我的请求标头以及它们的响应标头,这些标头显示该连接已升级到Websocket,并且为我分配了Sec-Websocket-Accept。然后,网络套接字立即关闭,没有任何响应通过。

我尝试过先向登录api发送发布请求,并生成sessionID和csrftoken,然后将其作为cookie传递到websocketapp对象中。没用我尝试过将标头作为实际的dict传递,但这也不起作用。我尝试了太多的b64编码变体,但没有一个起作用。

任何建议将不胜感激。

0 个答案:

没有答案
相关问题