WebSocket 为我们提供了便捷且实时的通讯能力。然而,对于 WebSocket 客户端的鉴权,协议的 RFC 是这么说的:
This protocol doesn’t prescribe any particular way that servers canauthenticate clients during the WebSocket handshake. The WebSocketserver can use any client authentication mechanism available to ageneric HTTP server, such as cookies, HTTP authentication, or TLSauthentication.
也就是说,鉴权这个事,得自己动手
协议原理
WebSocket 是独立的、创建在 TCP 上的协议。
为了创建Websocket连接,需要通过浏览器发出请求,之后服务器进行回应,这个过程通常称为“握手”。
实现步骤:
1. 发起请求的浏览器端,发出协商报文:
GET /chat HTTP/1.1Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
2、服务器端响应101状态码(即切换到socket通讯方式),其报文:
HTT