I finding a simple solution to use WebSocket with custom headers for web app based on PHP as backend and js+vuejs as frontend.
My app should connect to WebSocket server based on Java to get live stat. WebSocket server protected by Oauth2. So my app should add header like
"Authorization: bearer 647d14-b132-41b9-aa4c-9eafad5d9630 "
when connect to WS server. But i can't add this header because browser doesn't support custom headers. Answer on question about custom headers HTTP headers in Websockets client API
I need something like code below
var serverWs = "ws://servername/stat"; var opts = { reconnection: false, transports: ['websocket'], extraHeaders: { 'Authorization': 'Bearer xxxx' } } var ws = new WebSocket(serverWs, opts);
What's solution exists?
Note that the WebSockets protocol itself supports custom headers since it starts with a HTTP handshake similar to a normal HTTP request.
There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.
Fast Reaction TimeWebSockets allow for a higher amount of efficiency compared to REST because they do not require the HTTP request/response overhead for each message sent and received.
Some WebSockets security vulnerabilities arise when an attacker makes a cross-domain WebSocket connection from a web site that the attacker controls. This is known as a cross-site WebSocket hijacking attack, and it involves exploiting a cross-site request forgery (CSRF) vulnerability on a WebSocket handshake.
Websocket client API doesn't allow to send custom header, they allow you to set exactly one header, namely Sec-WebSocket-Protocol, i.e. the application specific subprotocol. You could use this header for passing the bearer token.
Other option is to use token in query string.
Or you can use some library on client or server which support custom headers implementation eg. https://github.com/crossbario/autobahn-python/tree/master/examples/twisted/websocket/echo_httpheaders
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With