Reputation: 1289
Is it possible to authenticate WebSocket handshake requests in Tornado? If so, how? If not, where can I check for authenticated user before the WebSocket is opened?
Upvotes: 2
Views: 1652
Reputation: 619
Your question specifically asks about authenticating before a websocket connection is opened.
If you're willing to allow the connection to be opened for authentication, then closed if authentication fails (still with the guarantee that no data is sent), then you'll need to define a condition in the open
method of your socket handler, which checks of the user is authenticated, and refuses to initialize a datastream otherwise (the WebSocketHandler source might be of interest here), closing the connection. Open is called on the initial handshake, but no data will be sent until the method returns. You can therefore close the connection before the listening endpoints are initialized.
You can check the request for an authenticated user with RequestHandler.current_user
: this is available in any handler, a WebSocketHandler
included.
You might also be using authentication cookies – you can access that cookie inside your socket handler simply by using self.request.headers
, or with get_secure_cookie
.
You have something like this, if you choose to use a cookie:
class SocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
user_slug = self.get_secure_cookie("user_cookie")
if user_slug:
...
else:
...
self.close()
...
If it's for some reason important that open
is never called, you might consider calling overriding get
from WebSocketHandler
, to preclude all initialization:
class SocketHandler(tornado.websocket.WebSocketHandler):
def get(self, *args, **kwargs):
if self.get_current_user():
...
super(SocketHandler, self).get(*args, **kwargs)
else:
...
Upvotes: 5