Home >Web Front-end >JS Tutorial >How Can I Add Custom HTTP Headers, Such as Authorization, to a WebSocket Client Connection in JavaScript?
HTTP headers in WebSocket Client API
Use any HTTP header client that supports this feature to customize the HTTP headers It seems easy to add a WebSocket client, but I can't find how to do this using the WebSocket API of the network platform.
Does anyone know how to implement it?
var ws = new WebSocket("ws://example.com/service");
Specifically, need to be able to send the HTTP Authorization header.
Updated
There is no method in the JavaScript WebSockets API to specify additional headers that the client/browser will send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.
The Sec-WebSocket-Protocol header (sometimes extended for use in WebSocket-specific authentication) is derived from WebSocket The optional second argument to the constructor generates:
var ws = new WebSocket("ws://example.com/path", "protocol"); var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);
The above code results in the following headers:
Sec-WebSocket-Protocol: protocol
and
Sec-WebSocket-Protocol: protocol1, protocol2
implement WebSocket A common pattern for authentication/authorization is to implement a ticket system, where the page hosting the WebSocket client requests a ticket from the server, which is then This ticket is passed during connection setup, either in the URL/query string, in the protocol field, or by specifying it as the first message after the connection is established. The server will then only allow the connection to continue if the ticket is valid (exists, has not been used, the client IP encoded in the ticket matches, the timestamp in the ticket is newer, etc.). The following is a summary of WebSocket security information: https://devcenter.heroku.com/articles/websocket-security.
Basic authentication used to be an option, but this has been deprecated and modern browsers will not send this header even if it is specified.
Basic Authentication Information (deprecated - no longer functional):
Authorization header is the username and password (or just username) fields from the WebSocket URI Generated:
var ws = new WebSocket("ws://username:password@")
The above code is generated with base64 Encode the following header for the string "username:password":
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Basic Authentication has been tested in Chrome 55 and Firefox 50 and verified that Basic Authentication information is indeed negotiated with the server (this May not work on Safari).
Thanks to Dmitry Frank for the basic authentication answer.
The above is the detailed content of How Can I Add Custom HTTP Headers, Such as Authorization, to a WebSocket Client Connection in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!