根據RFC 6455的WebSocket標準
first part:
.. the server has to prove to the client that it received the
client's WebSocket handshake, so that the server doesn't accept
connections that are not WebSocket connections. This prevents an
attacker from tricking a WebSocket server by sending it carefully
crafted packets using XMLHttpRequest [XMLHttpRequest] or a form
submission.
...
For this header field, the server has to take the value (as present
in the header field, e.g., the base64-encoded [RFC4648] version minus
any leading and trailing whitespace) and concatenate this with the
Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA-
95CA-C5AB0DC85B11" in string form, which is unlikely to be used by
network endpoints that do not understand the WebSocket Protocol.
second part:
The |Sec-WebSocket-Key| header field is used in the WebSocket opening
handshake. It is sent from the client to the server to provide part
of the information used by the server to prove that it received a
valid WebSocket opening handshake. This helps ensure that the server
does not accept connections from non-WebSocket clients (e.g., HTTP
clients) that are being abused to send data to unsuspecting WebSocket
servers.
所以,在標準中指定的GUID值,它是不可能(可能的話,以非常小的概率放置)不知道Websockets的服務器將會我使用它。它不提供任何安全性(安全的websockets - wss:// - 確實),它只是確保服務器理解websockets協議。
真的,正如你所說的,如果你知道websockets(這是要檢查的內容),你可以通過發送正確的響應,假裝是一個websocket服務器。但是,如果你不能正確行事(例如正確的表單框架),它將被視爲違反協議。其實,你可以寫一個不正確的websocket服務器,但是沒有太多用處。
而另一個目的是防止客戶意外地請求websockets升級不期望它(例如,通過手動添加相應的標題,然後希望別人)。 Sec-WebSocket-Key和其他相關頭文件禁止在瀏覽器中使用setRequestHeader
方法進行設置。
這是真的一些請求頭字段不能從XMLHttpRequest中的JavaScript修改,所以從瀏覽器的方式被阻止?但是如果有一個瀏覽器(可能是早期版本)可以修改Sec-websocket-key字段?或者如果請求是由程序發送來模擬瀏覽器,那麼您可以完全自行構建請求標頭,因此使Sec-WebSocket-Key無意義? – user2003548
請重新閱讀我的答案。即使您編寫的服務器或客戶端將模擬正確的升級請求,您也會在知道Websockest協議*存在*的情況下故意這樣做。 Sec-WebSocket-Key用於過濾_unintended_請求。如果您擔心安全 - 請使用安全的網絡套接字。 –
所以這個協議是基於ppl設計的,通常會使用它,如果面對一個惡意的軟件編寫器,它會像普通的http一樣搞砸了,我知道它是正確的嗎? – user2003548