乐闻世界logo
搜索文章和话题

What is Sec-WebSocket-Key for?

1个答案

1

Sec-WebSocket-Key is a critical HTTP header field used in the WebSocket handshake process. It helps the server verify that the connection request originates from a legitimate WebSocket client.

When establishing a WebSocket connection, the client generates a random string and sends it, after base64 encoding, as the value for Sec-WebSocket-Key to the server. This process is described as follows:

  1. The client generates a 16-byte random value.
  2. The client converts this random value to base64 format and sends it as the value for Sec-WebSocket-Key in the WebSocket upgrade request header.
GET
Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Version: 13``` When the server receives this request, it concatenates the value of Sec-WebSocket-Key with a specific GUID (Globally Unique Identifier, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"). Then, the server performs a SHA-1 hash operation on the concatenated string and base64 encodes the result. The encoded value is used as the value for Sec-WebSocket-Accept and returned to the client: ```HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=``` Upon receiving this response, the client compares the processed value of the original Sec-WebSocket-Key with the Sec-WebSocket-Accept value returned by the server. If they match, it indicates that the server is legitimate and correctly understands the WebSocket protocol, thereby establishing a secure WebSocket connection. This process prevents unauthorized or misleading connection requests and ensures that both parties can establish a secure and reliable communication channel.
2024年7月9日 15:48 回复

你的答案