Sails.js authorization for socket requests

2019-04-07 07:12发布

I'm trying to build a chat application based on sails.js. The url for messages from a specific chat looks like this:

/api/chat/:id/messages

When I request this url with XHR, it provides a session cookie and sails.js builds a session object. I can easily check user rights to read the messages from the specific chat.

However, I need to request this url with socket.io so that the client can subscribe to all future changes of the messages collection.

When I request this url with socket.io, no session cookie is set and the sails.js session is empty. So, I cannot check the user rights on the server-side.

I do understand that socket requests are not HTTP-requests. They don't provide any cookies on their own.

Is there any simple workaround?

4条回答
Root(大扎)
2楼-- · 2019-04-07 07:16

alevkon,in the above mentioned method you have to implement the same in all the controllers,because you don't know which controller is accessed for the first time...but by sending just one jsonp request you can create a cookie between client and server,the same cookie is used until the next session.

查看更多
做个烂人
3楼-- · 2019-04-07 07:18

please send a JSONP request from your application before sending a socket request,that will create a cookie and accepts socket requests.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-04-07 07:33

I found a way to get the session object which was set while socket.io handshaking. In your controller, you should do something like this:

myControllerAction: function(req, res) {
    var session = req.session;
    if (req.isSocket) {
        var handshake = req.socket.manager.handshaken[req.socket.id];
        if (handshake) {
            session = handshake.session;
        }
    }
    //session now contains proper session object
}

You can implement this in sails.js policy, and attach this policy to some controllers. But don't write you socket session into req.session! Otherwise, you'll get an error trying to respond to the client (original req.session is still used in some way). Instead, save it as req.socketSession or something like that.

查看更多
Juvenile、少年°
5楼-- · 2019-04-07 07:41

You can do your initial login over the socket.post() instead of XHR, subsequent socket requests will be authorized.

查看更多
登录 后发表回答