Under tornado v4+ WebSocket connections get refused with 403

前端 未结 2 1545
孤城傲影
孤城傲影 2021-01-31 12:01

I have an older tornado server that handles vanilla WebSocket connections. I proxy these connections, via Nginx, from wss://info.mydomain.com to wss://mydomain.com:8080 in order

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 12:33

    Tornado 4.0 introduced an, on by default, same origin check. This checks that the origin header set by the browser is the same as the host header

    The code looks like:

     def check_origin(self, origin):
        """Override to enable support for allowing alternate origins.
    
        The ``origin`` argument is the value of the ``Origin`` HTTP header,
        the url responsible for initiating this request.
    
        .. versionadded:: 4.0
        """
        parsed_origin = urlparse(origin)
        origin = parsed_origin.netloc
        origin = origin.lower()
    
        host = self.request.headers.get("Host")
    
        # Check to see that origin matches host directly, including ports
        return origin == host
    

    In order for your proxied websocket connection to still work you will need to override check origin on the WebSocketHandler and whitelist the domains that you care about. Something like this.

    import re
    from tornado import websocket
    
    class YouConnection(websocket.WebSocketHandler):
    
        def check_origin(self, origin):
            return bool(re.match(r'^.*?\.mydomain\.com', origin))
    

    This will let the connections coming through from info.mydomain.com to get through as before.

提交回复
热议问题