Requests and files Required
Check the origin of WebSocket connections
Accept a WebSocket connection only from your own origins, and only after checking the user's login, as for any other request.
How to do it
CORS does not cover WebSocket handshakes, and browsers send cookies with it from any site unless the cookie is marked SameSite=Lax or Strict. Compare the Origin header with your list during the handshake. Check the user's rights on each message that reads or changes data.
Example
curl -si --http1.1 --max-time 5 -H 'Connection: Upgrade' -H 'Upgrade: websocket' -H 'Sec-WebSocket-Version: 13' \
-H 'Sec-WebSocket-Key: QVctVEVTVC1rZXktMTIzNA==' -H 'Origin: https://evil.example.net' \
https://staging.example.com/ws | head -1 # 403, not 101
How to check
The agent opens a WebSocket to staging with Origin: https://evil.example.net and the test user's cookie. The handshake is refused.
For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers security testing playbook: https://agentwranglers.se/playbook/adversarial-testing/requests-and-files/websocket-origin.