PHP Websocket authenticate user in a test (pass session cookie) PHP Websocket authenticate user in a test (pass session cookie) php php

PHP Websocket authenticate user in a test (pass session cookie)


You have a cart before the horse situation here. When you set a cookie on a client connection that cookie is then only sent on subsequent requests (websockets or XHR, GET, POST, etc) provided the cookie restrictions (httpOnly, secure, domain, path, etc) match.

Any cookies available are sent during the initial handshake of the websocket connection. Setting a cookie on an open connection will set the cookie on the client but since the socket is already an open connection and established (post handshake) the server will be blind to those cookies for the duration of that connection.

Some people have had success setting the cookie during the handshake. However, that requires the server and client socket implementations supporting this behavior and passing credentials as get parameters (bad practice).

So I think your only real options are:

  • handle authentication through XHR or other request before opening a websocket
  • use the websocket for authentication, but then on successful login:
    • set your auth cookie
    • close the existing socket
    • initiate a new socket from the client (which will then carry your auth cookie)
  • forget cookies entirely and handle an authentication exchange on the server based on the request/resource ID for the open connection.

If you choose the last option you could still set the cookie and look for the cookie to restore connections on reconnects.