Search code examples
pythonwebsockettornado

tornado 403 GET warning when opening websocket


I found this python script which should allow me to open a WebSocket. However, I receive the warning [W 1402720 14:44:35 web:1811] 403 GET / (192.168.0.102) 11.02 ms in my Linux terminal when trying to open the actual WebSocket (using Old WebSocket Terminal Chrome plugin). The messages "connection opened", "connection closed" and "message received" are never printed in the terminal window.

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket

class MyHandler(tornado.websocket.WebSocketHandler):
        def open(self):
                print "connection opened"
                self.write_message("connection opened")

        def on_close(self):
                print "connection closed"

        def on_message(self,message):
                print "Message received: {}".format(message)
                self.write_message("message received")

if __name__ == "__main__":
        tornado.options.parse_command_line()
        app = tornado.web.Application(handlers=[(r"/",MyHandler)])
        server = tornado.httpserver.HTTPServer(app)
        server.listen(8888)
        tornado.ioloop.IOLoop.instance().start()

Solution

  • please add

    def check_origin(self, origin):
        return True
    

    in class MyHandler like this

    class MyHandler(tornado.websocket.WebSocketHandler):
    
        def check_origin(self, origin):
            return True
    
        def open(self):
            print "connection opened"
            self.write_message("connection opened")
    
        def on_close(self):
            print "connection closed"
    
        def on_message(self,message):
            print "Message received: {}".format(message)
            self.write_message("message received")
    

    From the DOCs:

    By default, [check_origin] rejects all requests with an origin on a host other than this one.

    This is a security protection against cross site scripting attacks on browsers, since WebSockets are allowed to bypass the usual same-origin policies and don’t use CORS headers.

    And again:

    This is an important security measure; don’t disable it without understanding the security implications. In particular, if your authentication is cookie-based, you must either restrict the origins allowed by check_origin() or implement your own XSRF-like protection for websocket connections. See these articles for more.

    Link.