Monday, 13 March 2017

Sails socket authorization (using passport)

I am using passport for authentication/authorization along with local strategy and a JWT.

Following some research (intensive googling ;) I understand that the best place for the authorization is to use a policy as it applies both for a regular HTTP requests and a socket request (through SailsSocket object that can send 'virtual' HTTP-like requests).

I am now trying to figure out how to use sockets properly and I've seen that there's a beforeConnect handler that allows to reject a connection. While it is not a big deal (as I have a policy that will prevent it from getting data), I want to be able to reject connections - I think its healthier and what reason is there to allow a non-authorized socket connection.

I only want to socket to connect after initial authentication so that in my socket initialization I can set the headers to include the JWT:

io.sails.url = connections.http.baseURL;

io.sails.headers = {
    'Authorization': 'Bearer ' + token
};

io.sails.useCORSRouteToGetCookie = false;

io.socket = io.sails.connect();
io.socket.on('...', someHandler);

This seems to work fine - the socket request hits the JWT policy and I get a req.user in my controller methods for socket requests.

My question is - how do I go about rejecting the user without a token from connecting (and should I even do that?)

When I break inside the beforeConnect I don't see the Authorization header in handshake object.

Am I missing something?



via Tomer Cagan

No comments:

Post a Comment