简体   繁体   中英

Websocket: maintain user session after page reloading

I've got a simple Single Page Application using jetty websockets for communication between server and client.

Problem: Each time I have reload page my websocket connection is disabled and new is initialized. The problem is that user should relogin on each page refresh.

Question: How can I eliminate the need of relogin on page refresh?

EDITED: Faced the next problem : how to decide when session should be deleted? I've a peer object on the server side which is a nothing else but websocket session container. Peer is deleted on onClose method, which in turn is invoked on droping client side websocket. Here the problem comes: when user press F5 -> client side websocket is broken -> server delete appropriate websocket -> client side try to reload a page and check if there is any session AND FIND NOTHING. On the other hand I can't cease removing y peers (sessions) at all.

Question: How can I tell server when to remove my peers?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM