16

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?

wonea
  • 4,783
  • 17
  • 86
  • 139
maxxdev
  • 313
  • 2
  • 5
  • 14

1 Answers1

5

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

mdeora
  • 4,152
  • 2
  • 19
  • 29