将 WebSocket 升级到 TLS

Upgrading WebSockets to TLS

对于 HTTP,可以使用 301 响应将所有请求升级到 HTTPS。

然而,对于websocket来说,似乎并没有那么容易。如果我将 ws://127.0.0.1 请求重定向到 wss:/127.0.0.1,我会在浏览器中使用 websocket.org 上的测试得到一个 "error: undefined"(是的,证书是可信的并且适用于wss 如果直接使用)。发出初始请求,并发送重定向。但是,在 TLS 端口上没有第二个请求。

规范仅简要介绍了重定向。

这取决于 webSocket 客户端实现是否处理 3xx 状态代码。 webSocket specification 不需要客户端实现来这样做。这是规范中的引述:

If the status code received from the server is not 101, the client handles the response per HTTP [RFC2616] procedures. In particular, the client might perform authentication if it receives a 401 status code; the server might redirect the client using a 3xx status code (but clients are not required to follow them), etc. Otherwise, proceed as follows.

For HTTP, it is possible to upgrade all requests to HTTPS with a 301 response.

(挑剔)这并不是真正的请求升级,而是导致不同请求的重定向。

Is upgrading ws to wss possible?

根据 websocket standard (RFC 6455):

If the status code received from the server is not 101, the client handles the response per HTTP [RFC2616] procedures. In particular, the client might perform authentication if it receives a 401 status code; the server might redirect the client using a 3xx status code (but clients are not required to follow them), etc.

所以是的,某些客户端可能支持它,但其他客户端不支持。例如,在 Firefox 中,相关的 属性 network.websocket.auto-follow-http-redirects 默认为 false,即默认情况下它不遵循重定向。

Do I need to send WebSocket specific headers even with the redirect response?

这些仅与将请求升级到 websocket 无关,与重定向无关。这意味着 headers 应该只在升级响应(状态代码 101)中发送。