2

When I set up a websocket connection from JavaScript, how can I authorize that it is a legit user on the serverside? I am using JSON Web Tokens and when doing regular calls to REST backend I automatically add an Authorization: Bearer (JWT..) header on AngularJS and then check that on the server side to see if a user is logged in. How can I do that when upgrading the connection to a websocket connection? I am afraid that some people with connect to the server requesting a websocket connection and spoof some of the users id's and receive their messages without being logged in to the service.

I request a websocket connection like this:

var conn = new WebSocket("ws://localhost:8080/api/ws");

conn.onclose = function (e) {
    console.log("disconnected");
};

conn.onopen = function (e) {
    console.log("connected");
};

conn.onmessage = function (e) {
    console.log(e.data);
};

On the first part, is that a GET request or a POST request? Can I add parameters to the url and check them on the serverside? For example:

var conn = new WebSocket("ws://localhost:8080/api/ws/token/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ");

Or is this not a good idea? I also thought sending a JWT would be a good idea because I would be able to extract the user_id from the JWT and associate a websocket connection to a specific user.

How can I solve this problem?

Alex
  • 5,671
  • 9
  • 41
  • 81
  • you can use cookies as described here http://stackoverflow.com/questions/23493899/authenticate-websocket-clients-using-tokens – Amitd Sep 19 '15 at 14:46
  • what if I sent the token as a first message? would that be secure? – Alex Sep 19 '15 at 15:23
  • no it has to be sent in all requests..if a valid session is taken over then you wont be able to find out. – Amitd Sep 19 '15 at 16:20
  • That is odd, in this page it seems they claim that the handshake is the most cruical part. https://auth0.com/blog/2014/01/15/auth-with-socket-io/ I have the ability to store connections on the serverside and associate them to user_Id, if the connection with the client is lost I can just remove and delete the connection from the serverside. I don't understand why you need the token on every request? Also on this thread http://stackoverflow.com/questions/10028770/html5-websocket-vs-long-polling-vs-ajax-vs-webrtc-vs-server-sent-events it says that once the connection is up, it is hard to sniff. – Alex Sep 20 '15 at 12:04
  • Have a loook at: https://auth0.com/blog/2014/01/15/auth-with-socket-io/ – Johannes Ferner Sep 22 '15 at 22:18

0 Answers0