跳到主要内容
uencoder

如何Implement 安全 WebSockets

Establish 和 maintain 安全 WebSocket (WSS) connections 具有 proper 认证, 源 validation, 和消息完整性.

问题

WebSocket connections 能够是 hijacked, lack 认证, 或接受 messages 从未授权 origins. 你需要implement 安全 WebSockets (wss://) 具有 proper 认证, 源 checking, 和保护针对常见 attacks.

前置条件

  • Understanding 的 WebSocket 协议 (RFC 6455)
  • 熟悉TLS 和 wss:// scheme
  • Knowledge 的 HTTP 认证和 CORS

步骤

  1. 1. Establish WSS with TLS and authentication

    Always use wss:// (WebSocket Secure over TLS), never ws:// in production. Perform authentication during the WebSocket handshake: pass a token in the initial HTTP upgrade request (via Authorization header, query parameter, or Sec-WebSocket-Protocol subprotocol). Validate the token before accepting the upgrade. The server must reject the upgrade (HTTP 401/403) if authentication fails. Use the WebSocket frame encoder/decoder to understand the protocol.

    输入
    GET /ws HTTP/1.1 | Upgrade: websocket | Authorization: Bearer <token>
    输出
    HTTP 101 Switching Protocols (if auth valid) | HTTP 401 (if auth fails)
  2. 2. Validate the Origin header

    Check the Origin header on the upgrade request against an allow-list of trusted origins. This prevents Cross-Site WebSocket Hijacking (CSWSH) where a malicious website opens a WebSocket to your server using the victim's browser credentials. Reject requests with missing or untrusted origins with HTTP 403. Do not use CORS for WebSockets — Origin checking is the WebSocket-specific mechanism. Use the URL parser to validate origin format.

    输入
    Origin: https://trusted.example.com
    输出
    origin_check: pass | (Origin: https://evil.com -> reject 403)
  3. 3. Implement message validation and rate limiting

    Validate every incoming message against a schema (JSON Schema, protobuf) before processing. Reject malformed, oversized, or unexpected message types. Enforce a maximum message size (e.g., 1MB) and rate limit per connection (messages per second). Use ping/pong frames for keepalive and to detect dead connections. Set reasonable timeouts for idle connections. Use the JSON validator and WebSocket frame decoder for message inspection.

    输入
    message: { type: chat, text: hello }
    输出
    valid: true | processed | (oversized: reject 1009 Message Too Big)
  4. 4. Secure the connection lifecycle

    Implement proper connection cleanup: close connections on authentication expiry, set idle timeouts, and handle close codes (1000 normal, 1001 going away, 1008 policy violation, 1011 internal error). Re-authenticate on reconnection. Never send sensitive data in broadcast messages. Log connection events for audit. For multi-server deployments, use a shared session store and authenticate on each server, not just the one that received the upgrade.

    输入
    token expired mid-session
    输出
    close: 1008 Policy Violation | reason: auth expired

预期结果

安全 WebSocket connections 具有 TLS, per-连接认证, 源 validation, 消息模式 enforcement, 和速率 limiting.

常见错误

Using ws:// instead of wss:// in production
Always use wss:// (TLS). ws:// sends all data including tokens in plaintext, vulnerable to interception and modification.
Not validating the Origin header
Without Origin validation, any website can open a WebSocket to your server using the user's browser session. Always check Origin against an allow-list.
Authenticating only at connection, not per-message
For long-lived connections, the initial token may expire. Re-validate periodically or on sensitive operations. Close connections with expired credentials.

排障指引

  • If connections drop frequently, check proxy/load balancer WebSocket support and timeout settings (e.g., Nginx proxy_read_timeout).
  • If the Origin check blocks legitimate connections, ensure your CDN/proxy forwards the Origin header correctly.
  • For large messages, consider chunking or using a separate file upload channel rather than sending large payloads over WebSocket.

安全限制

  • WebSocket connections are stateful and long-lived — a compromised token remains valid until the connection closes or the token is re-validated.
  • All authentication and message validation happen server-side; the client must not be trusted to enforce security policies.
  • Broadcast messages can leak data to unauthorized clients if not filtered per-recipient.

相关工具

WebSocket 帧编码器
Websocket Frame Encode — 纯客户端工具。隐私优先,无服务器往返。
工具
WebSocket 帧解码器
Websocket Frame Decode — 纯客户端工具。隐私优先,无服务器往返。
工具
JWT 解码器
解码并检查 JWT 头部、载荷和时间声明及过期状态。免费、隐私优先、100% 纯客户端运行。本地解析不视为服务端验签。支持 HS256/RS256 等算法头部解析、exp/iat/nbf 时间声明展示,并标注 EXPIRED/NOT YET VALID/VALID 状态。
工具
OAuth Token 解析器
Oauth Token Parser — 纯客户端工具。隐私优先,无服务器往返。
工具
Bearer Token 生成器
由 token 字符串构造「Bearer <token>」Authorization 头(RFC 6750)。token 会按 b64token 语法校验——字母、数字、-._~+/ 与结尾「=」之外的字符会被拒绝(可防止头部注入)。
工具
URL 解析器
将 URL 解析为各组成部分:协议、主机、路径、查询、哈希、端口、用户名和密码。免费、隐私、100% 客户端运行。
工具
JSON 验证器
验证 JSON 并按行列定位语法错误。免费、隐私本地化、100% 客户端运行。
工具
HTTP 状态码参考
常见 HTTP 状态码(1xx-5xx)参考表,包含名称、类别和描述。免费、隐私、100% 客户端运行。
工具
哈希计算器
计算 MD5、SHA-1、SHA-256 或 SHA-512 哈希,支持十六进制或 Base64 输出。免费、隐私、100% 客户端运行。SHA-256/512 基于 Web Crypto API,MD5 基于 spark-md5,适用于校验和、完整性验证、指纹识别等场景。MD5 与 SHA-1 已不适用于安全场景。
工具

相关词条

参考链接