WebSocket handshake is a process of upgrading from HTTP protocol to WebSocket protocol, implemented through HTTP Upgrade mechanism.
Detailed Handshake Process
1. Client Initiates Handshake Request
Client sends a special HTTP GET request with the following key header fields:
shellGET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Key Headers Explanation:
Upgrade: websocket: Tells server client wants to upgrade to WebSocket protocolConnection: Upgrade: Indicates this is an upgrade connectionSec-WebSocket-Key: Random string generated by client for server verificationSec-WebSocket-Version: WebSocket protocol version, currently 13Sec-WebSocket-Protocol: Optional, specifies sub-protocolSec-WebSocket-Extensions: Optional, specifies extension features
2. Server Verifies and Responds
After receiving request, server performs following verification:
- Verify
Sec-WebSocket-Keyexists - Concatenate
Sec-WebSocket-Keywith GUID258EAFA5-E914-47DA-95CA-C5AB0DC85B11 - Perform SHA-1 hash on concatenated string
- Base64 encode the hash result
- Put encoded result in
Sec-WebSocket-Acceptheader
Server response:
shellHTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat
3. Connection Successfully Established
After server returns 101 status code, HTTP connection upgrades to WebSocket connection, both parties start communicating using WebSocket data frames.
Handshake Security
Preventing Cross-Site WebSocket Hijacking (CSWSH)
Originheader verification: Server checks request sourceSec-WebSocket-Keyverification: Prevents cache poisoning attacks
Best Practices
- Use WSS (WebSocket Secure) encrypted connections
- Verify
Originheader - Implement proper authentication mechanisms
- Limit connection frequency