Home >Web Front-end >JS Tutorial >How Can I Add Custom HTTP Headers to My WebSocket Client in JavaScript?
HTTP Headers in Websocket Client API
The WebSocket API provides a straightforward way to add custom HTTP headers to your client. However, it's worth noting that only certain headers can be specified.
Customization Limitations
Contrary to belief, the JavaScript WebSockets API does not allow you to specify arbitrary HTTP headers. Only the path and protocol fields can be set. The path is specified in the WebSocket constructor's first argument, while the protocol header is specified in its optional second argument.
Specifying Protocol Header
var ws = new WebSocket("ws://example.com/path", "protocol");
The above code generates the following header:
Sec-WebSocket-Protocol: protocol
You can also specify multiple protocols:
var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);
Resulting in the following header:
Sec-WebSocket-Protocol: protocol1, protocol2
Authentication/Authorization
A common approach for authenticating over WebSockets is to use a ticketing system. The server generates a ticket that the client includes in the URL, protocol field, or the first message after connection. The server then validates the ticket and proceeds or denies the connection accordingly.
Basic Authentication (Deprecated)
Basic authentication was previously accepted, but has been deprecated and is no longer supported by modern browsers.
Additional Notes
It's worth mentioning that the Authorization header could be generated from the username and password in the WebSocket URI (though this method is also deprecated).
To learn more about WebSocket security, refer to this article: https://devcenter.heroku.com/articles/websocket-security
The above is the detailed content of How Can I Add Custom HTTP Headers to My WebSocket Client in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!