關於http headers 在 Websockets client API 中的正確操作
由於這段時間要處理websocket一些問題,要在WebSocket連接過程中使用最基礎的用戶名密碼驗證,但是一直沒有找到怎麽處理,然後詳細閱讀了RFC6455文檔,然後才知道怎麽處理。當然本方最後也找到一個詳細的問題描述與解決方案:HTTP headers in Websockets client API
這個原題目就是:HTTP headers in Websockets client API
解決方案是:
There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. However the HTTP path ("GET /xyz"), basic auth header ("Authorization") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.
The Authorization header is generated from the username and password (or just username) field of the WebSocket URI:
var ws = new WebSocket("ws://username:[email protected]")
The above results in the following header with the string "username:password" base64 encoded:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
I have tested basic auth in Chrome 55 and Firefox 50 and verified that the basic auth info is indeed negotiated with the server (this may not work in Safari).
The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor:
var ws = new WebSocket("ws://example.com/path", "protocol"); var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);
The above results in the following headers:
Sec-WebSocket-Protocol: protocol
and
Sec-WebSocket-Protocol: protocol1, protocol2
其實還有以下的方案:
HTTP Authorization header problem can be addressed with the following:
var ws = new WebSocket("ws://username:[email protected]/service");
Then, a proper Basic Authorization HTTP header will be set with the provided username
and password
. If you need Basic Authorization, then you‘re all set.
want to use Bearer
however, and I resorted to the following trick: I connect to the server as follows:
var ws = new WebSocket("ws://[email protected]/service");
And when my code at the server side receives Basic Authorization header with non-empty username and empty password, then it interprets the username as a token.
關於http headers 在 Websockets client API 中的正確操作