龙卷风403打开网络时收到警告

2024-04-25 12:17:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了这个python脚本,它应该允许我打开一个WebSocket。 但是,当我试图打开实际的WebSocket(使用旧的WebSocket终端Chrome插件)时,我在Linux终端收到警告[W 1402720 14:44:35 web:1811] 403 GET / (192.168.0.102) 11.02 ms。“连接已打开”、“连接已关闭”和“消息已接收”消息从未在终端窗口中打印。

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()

Tags: importselfweb终端消息messagedefconnection
3条回答

稍微修改了@maxhawkdown的解。

from tornado.util import PY3

if PY3:
    from urllib.parse import urlparse  # py2

    xrange = range
else:
    from urlparse import urlparse  # py3


class ChatHandler(tornado.websocket.WebSocketHandler):
    CORS_ORIGINS = ['localhost']

    def check_origin(self, origin):
        parsed_origin = urlparse(origin)
        # parsed_origin.netloc.lower() gives localhost:3333
        return parsed_origin.hostname in self.CORS_ORIGINS

不要将check_origin()设置为return True,因为它是security threat,请使用允许的域列表,即:

def check_origin(self, origin):
    allowed = ["https://site1.tld", "https://site2.tld"]
    if origin in allowed:
        print("allowed", origin)
        return 1

请加上

def check_origin(self, origin):
    return True

类中的MyHandler如下

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")

从文档中:

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.

再说一遍:

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

相关问题 更多 >