Websocket: maintain user session after page reloading

ぐ巨炮叔叔 提交于 2019-12-03 09:07:16

To eliminate the need to authenticate a WebSocket connection upon each new connection establishment you can use cookies.

Authenticate the WebSocket connection upon first time, set cookie on the WebSocket connection, and recheck the cookie upon a new connection.

This requires a WebSocket server that allows to read and set cookies on a WebSocket connection.

If the WebSocket connection is served from the same origin as the HTML page containing the JavaScript that opens the WebSocket connection, you could also use a "normal" HTML form based login plus cookie procedure:

  1. User opens "login.html", which contains a HTML form for login
  2. User enters username/password, which submits the HTML form via HTTP/POST to some URL
  3. The server checks the credentials, and when successful, generates a random cookie, stores the cookie, and sets the cookie on the HTML page returned from the HTTP/POST
  4. This latter returned page then opens a WebSocket connection to the server (which is on same origin, and hence the previously set cookie is set)
  5. The WebSocket server in the opening handshake checks if there is a cookie, and if the cookie is stored in the DB for logged-in users
  6. If so, the WebSocket connection succeeds. If not, the WebSocket server does not establish a connection, but redirects the user to 1.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!