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

和自甴很熟 提交于 2019-12-03 23:27:09

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!