AnilJ
AnilJ

Reputation: 2121

How to create a python websocket with SSL and use a cookie in it?

There is a way to create the websocket with SSL argument like below.

ws = create_connection("ws://{0}/socket{1}".format(ip_addr, cookie),
                       sslopt={"cert_reqs": ssl.CERT_NONE,
                               "check_hostname": False,
                               "ssl_version": ssl.PROTOCOL_TLSv1})

From an example here, one of the ways to create the websocket connection is as below. However, it is not given how do I pass the SSL arguments like done above?

What is the way to use 'WebSocketApp' with SSL arguments as well as pass the cookie to it?

if __name__ == "__main__":
    websocket.enableTrace(True)
    if len(sys.argv) < 2:
        host = "ws://echo.websocket.org/"
    else:
        host = sys.argv[1]
    ws = websocket.WebSocketApp(host,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()

Upvotes: 2

Views: 6171

Answers (1)

AnilJ
AnilJ

Reputation: 2121

  • I figured the way to pass the cookie to the connection as below. The cookie is encoded in the URL itself. Note: Please refer to the URL components per your server implementation. The ip_addr, port, and cookie can be a local parameters.

    url = "ws://{0}:{1}/socket{2}".format(str(ip_addr), str(port), cookie)
    

    Pass this URL when creating the websocket connection. Please refer to original question to see where URL is passed.

  • I also found an answer pass the SSL parameters from a reference here

    import ssl
    
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE,
                       "check_hostname": False,
                       "ssl_version": ssl.PROTOCOL_TLSv1})
    

Both these changes worked in my case.

Upvotes: 4

Related Questions