Python Websockets results in Handshake status 503

eiten 10 years ago

Hi everyone,

I try to write a small python daemon that looks for events and then sends messages with telegram. The first test script looks like this:

import websocket
import thread
import time
import base64

auth = base64.b64encode('admin:admin')

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        while True:
            time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:8082/api/socket",
                              on_message = on_message,
                              on_error   = on_error,
                              on_close   = on_close,
                              header     = {"authorization: Basic " + auth }
                              )
    ws.on_open = on_open
    ws.run_forever()

But this does not work, I get a handshake error:

--- request header ---
GET /api/socket HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8082
Origin: http://localhost:8082
Sec-WebSocket-Key: lTKj+s4VECV+UAvpUfDLcg==
Sec-WebSocket-Version: 13
authorization: Basic YWRtaW46YWRtaW4=

-----------------------
--- response header ---
HTTP/1.1 503 Endpoint Creation Failed
Date: Fri, 12 May 2017 14:16:53 GMT
Content-Type: text/html; charset=ISO-8859-1
Cache-Control: must-revalidate,no-cache,no-store
Content-Length: 99
Server: Jetty(9.2.21.v20170120)
-----------------------
Handshake status 503
### closed ###

Any ideas anyone

Anton Tananaev 10 years ago

For WebSocket connection you have to use cookie session authentication. It doesn't support HTTP authorisation header option.

eiten 10 years ago

Ah thanks a lot. I'll try!

eiten 10 years ago

Great, it works! Thanks a lot.
For reverence, that's the code:

import websocket
import thread
import time
import requests
import urllib
###########################################################################
# configuration
###########################################################################
email    = 'email'
password = 'password'
url      = 'localhost:8082'

# Get session token
###################
session = requests.Session()
params = urllib.urlencode({'email': email, 'password': password})

headers = {'content-type': 'application/x-www-form-urlencoded',
           'accept': 'application/json'}

response = session.post('http://' + url + '/api/session',
                        data=params,
                        headers=headers)

cookies = session.cookies.get_dict()
token= cookies['JSESSIONID']

if response.status_code == 200:
        print "Authentication successfull, Token: ", token
else:
        print "Authentication failed, Status:", response.status_code
        quit()

# Websocket connection
######################
def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        while True:
            time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:8082/api/socket",
                              on_message = on_message,
                              on_error   = on_error,
                              on_close   = on_close,
                              header     = {"Cookie: JSESSIONID=" + token }
                              )
    ws.on_open = on_open
    ws.run_forever()