Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom headers for WebSocket JS

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?

like image 741
maxxdev Avatar asked Oct 04 '16 13:10

maxxdev


People also ask

Can WebSocket have headers?

Note that the WebSockets protocol itself supports custom headers since it starts with a HTTP handshake similar to a normal HTTP request.

How do I pass headers to WebSockets?

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.

Is WebSocket Faster Than REST API?

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.

Can WebSocket be hacked?

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.


1 Answers

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

like image 96
mdeora Avatar answered Oct 17 '22 22:10

mdeora