简体   繁体   中英

Websocket client not working for wss using python code

I am using python client to connect to a server hosted in azure. I am using websockets to connect. I am passing the auth header in the python client code. The code doesn't work when we give wss:// url for connection. The error says:

Handshake status 403 Forbidden

However same thing is working when tested using postman.

Here is the code snippet used to connect to the websocket server:

def on_message(ws, message):
    print(message)

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

def on_close(ws, close_status_code, close_msg):
    print("### closed ###")

def on_open(ws):
    print("Opened connection")

auth_str = "Authorization:Basic abgvrgfrbnfrfurfr"

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://uri.com/websocket",
                             header=[auth_str],
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close
                              )
    ws.run_forever(dispatcher=rel) 
    rel.signal(2, rel.abort)  
    rel.dispatch()

The request headers of the requests in postman and python client have no difference. Don't know why the python client says 403 forbidden .

It is only working under one condition: Setting HTTPSOnly as false in app service and passing ws:// uri instead of wss://

As I see, your header parameter definition is wrong. It needs to be like

ws = websocket.WebSocketApp("wss://uri.com/websocket",
                             header={ 'Authorization': 'Basic abgvrgfrbnfrfurfr' },
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close
                              )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM