Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication before opening a Websocket

What is the State-of-the-art way to secure a websocket with authentication?

The problem is, that everybody can download the js file and see the host and port to which websocket the page connects. The only way which comes to my mind is: open a wss(secure websocket) and send for example credentials and close the connection on the server-side if the credentials are wrong?

like image 344
user2071938 Avatar asked Jul 31 '26 16:07

user2071938


1 Answers

First of all, a WebSocket request has an Origin HTTP header that indicates the domain where the client is running. So if your site is www.whatever.com, and you get a WebSocket request with a www.smartass.com as origin, you can reject it. That will prevent other from letting users connect to your service inadvertently. That said, it is still possible to access your service from everywhere by faking that header, but must be done on purpose.

WebSockets uses HTTP negotiation, so they can carry cookies during negotiation. If your WebSocket service is in the same domain or subdomain that the rest of your site you can share cookies. So for example, when your user logins successfully, a cookie will be returned that he will use to authenticate himself in each HTTP interaction with the server, including the WebSocket service. Just reject any request without valid cookies and you are done.

If they are in different domains, you can do what you said, use a loginRequest/loginResponse messages to authenticate the connection.

like image 167
vtortola Avatar answered Aug 03 '26 06:08

vtortola