Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a WebSocket key work?

Recently I have been researching WebSockets, I think they are very cool. However, if I take a look here, some things are unclear for me.

Request:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

Response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

The requester specifies the host, so intermediate servers will know where the request should arrive. The requester sends a random string encoded into base64 and the server sends back a salted SHA1-encrypted key back. Will this key be used between the two while the connection is alive? If so, is there a way this key can be reused even if the connection was broken?

like image 899
Lajos Arpad Avatar asked Sep 17 '16 10:09

Lajos Arpad


1 Answers

As it's mentioned in your Wikipedia link:

In addition to Upgrade headers, the client sends a Sec-WebSocket-Key header containing base64-encoded random bytes, and the server replies with a hash of the key in the Sec-WebSocket-Accept header. This is intended to prevent a caching proxy from re-sending a previous WebSocket conversation, and does not provide any authentication, privacy or integrity.

Sec-WebSocket-Key is only used inside the handshake and isn't used for the actual communication.

The key is meant to prevent proxies from caching the request, by sending a random key. If the proxy still returns a cached response, it can be checked by validating the Sec-WebSocket-Accept header.

The client could ignore the Sec-WebSocket-Accept header (and hope the response isn't cached) and the WebSocket protocol would still work normally.
In such case the server could be implemented to ignore the Sec-WebSocket-Key header and not return the Sec-WebSocket-Accept header.

How to generate the Sec-WebSocket-Accept header for response or validation can be read inside this answer:
generate "Sec-WebSocket-Accept" from "Sec-WebSocket-Key"

like image 57
gre_gor Avatar answered Nov 15 '22 06:11

gre_gor