384

Looks like it's easy to add custom HTTP headers to your websocket client with any HTTP header client which supports this, but I can't find how to do it with the web platform's WebSocket API.

Anyone has a clue on how to achieve it?

var ws = new WebSocket("ws://example.com/service");

Specifically, I need to be able to send an HTTP Authorization header.

12
  • 29
    I think a good solution is to allow the WebSocket to connect without authorization, but then block and wait on the server to recieve authorization from the webSocket which will transmit authorization information in its onopen event.
    – Motomotes
    Dec 28, 2015 at 15:57
  • The suggestion by @Motes seems to be the best fit. It was very easy to make an authorization call from onOpen which allows you to accept/reject the socket based on the authorization response. I originally attempted sending auth token in Sec-WebSocket-Protocol header but that feels like a hack. Oct 29, 2017 at 3:59
  • 1
    @Motes Hi, could you explain the "block and wait on the server" part ? you mean something like don't process any messages till there's a "auth" message ?
    – Himal
    Aug 18, 2019 at 4:44
  • @Himal, yes the server design must not send data or accept any other data than authorization in the beginning of the connection.
    – Motomotes
    Aug 18, 2019 at 10:37
  • @Motes Thanks for the reply. I was bit confused by the blocking part, becasue to my understanding you can't block the initial connect request. I'm using Django channels on the back end and I've designed it to accept the connection on connect event. it then sets an "is_auth" flag in the receive event (if it sees a valid auth message). if the is_auth flag isn't set and it's not an auth message then it closes the connection.
    – Himal
    Aug 18, 2019 at 14:40

18 Answers 18

373

Updated 2x

Short answer: No, only the path and protocol field can be specified.

Longer answer:

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.

The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor:

var ws = new WebSocket("ws://example.com/path", "protocol");
var ws = new WebSocket("ws://example.com/path", ["protocol1", "protocol2"]);

The above results in the following headers:

Sec-WebSocket-Protocol: protocol

and

Sec-WebSocket-Protocol: protocol1, protocol2

A common pattern for achieving WebSocket authentication/authorization is to implement a ticketing system where the page hosting the WebSocket client requests a ticket from the server and then passes this ticket during WebSocket connection setup either in the URL/query string, in the protocol field, or required as the first message after the connection is established. The server then only allows the connection to continue if the ticket is valid (exists, has not been already used, client IP encoded in ticket matches, timestamp in ticket is recent, etc). Here is a summary of WebSocket security information: https://devcenter.heroku.com/articles/websocket-security

Basic authentication was formerly an option but this has been deprecated and modern browsers don't send the header even if it is specified.

Basic Auth Info (Deprecated - No longer functional):

NOTE: the following information is no longer accurate in any modern browsers.

The Authorization header is generated from the username and password (or just username) field of the WebSocket URI:

var ws = new WebSocket("ws://username:[email protected]")

The above results in the following header with the string "username:password" base64 encoded:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

I have tested basic auth in Chrome 55 and Firefox 50 and verified that the basic auth info is indeed negotiated with the server (this may not work in Safari).

Thanks to Dmitry Frank's for the basic auth answer

23
  • 84
    I've come across the same problem. Too bad that these standards are so poorly integrated. You'd expect that they look at the XHR API to find requirements (since WebSockets and XHR are related) for the WebSockets API, but it seems they are just developing the API on an island by itself. May 1, 2012 at 14:26
  • 4
    @eleotlecram, join the HyBi working group and propose it. The group is open to the public and there is ongoing work for subsequent versions of the protocol.
    – kanaka
    May 1, 2012 at 18:59
  • 8
    @Charlie: if you fully control the server, that's one option. The more common approach to is generate a ticket/token from your normal HTTP server and then have the client send the ticket/token (either as a query string in the websocket path or as the first websocket message). The websocket server then validates that the ticket/token is valid (hasn't expired, hasn't already been used, coming from same IP as when created, etc). Also, I believe most websockets clients support basic auth (may not be enough for you though). More info: devcenter.heroku.com/articles/websocket-security
    – kanaka
    Jun 4, 2014 at 17:57
  • 3
    I guess its by design. I am under the impression that the implementation is intentionally borrowing from HTTP but keep them separated as much as possible by design. The text in the specificatio continues: "However, the design does not limit WebSocket to HTTP, and future implementations could use a simpler handshake over a dedicated port without reinventing the entire protocol. This last point is important because the traffic patterns of interactive messaging do not closely match standard HTTP traffic and can induce unusual loads on some components."
    – user1441149
    Sep 14, 2016 at 18:54
  • 4
    Unfortunately this doesn't seem to work in Edge. Thanks, MS :/
    – sibbl
    Feb 21, 2017 at 11:07
88

More of an alternate solution, but all modern browsers send the domain cookies along with the connection, so using:

var authToken = 'R3YKZFKBVi';

document.cookie = 'X-Authorization=' + authToken + '; path=/';

var ws = new WebSocket(
    'wss://localhost:9000/wss/'
);

End up with the request connection headers:

Cookie: X-Authorization=R3YKZFKBVi
12
  • 10
    what if the WS server URI is different from client URI?
    – Danish
    May 7, 2020 at 0:11
  • 13
    @Danish Well then that doesn't work, since you cannot set cookies for other domains client side
    – Tofandel
    Jul 3, 2020 at 20:12
  • 5
    But, you can set up an HTTP service that sets a session cookie on the relevant path, and call that before starting your websocket. Call, say, https://example.com/login, and have the response set a cookie on /wss then new WebSocket("wss://example.com/wss") will start its handshake request with the relevant cookie. Note that the devtools might not show the cookie, but it should still be sent.
    – Coderer
    Jul 9, 2020 at 12:52
  • 12
    Websocket requests are not subject to the same origin policy. Sending authentication as a cookie will open up your application to hijacking. See christian-schneider.net/CrossSiteWebSocketHijacking.html Oct 19, 2020 at 18:43
  • 5
    Christian Schneider (the author of the article above) suggests using CSRF-Tokens to protect initial HTTP handshake, when using Authentication Cookie: ws = new WebSocket("wss://example.com/wss?csrftoken=<token>") Mar 30, 2021 at 10:31
42

Sending Authorization header is not possible.

Attaching a token query parameter is an option. However, in some circumstances, it may be undesirable to send your main login token in plain text as a query parameter because it is more opaque than using a header and will end up being logged whoknowswhere. If this raises security concerns for you, an alternative is to use a secondary JWT token just for the web socket stuff.

Create a REST endpoint for generating this JWT, which can of course only be accessed by users authenticated with your primary login token (transmitted via header). The web socket JWT can be configured differently than your login token, e.g. with a shorter timeout, so it's safer to send around as query param of your upgrade request.

Create a separate JwtAuthHandler for the same route you register the SockJS eventbusHandler on. Make sure your auth handler is registered first, so you can check the web socket token against your database (the JWT should be somehow linked to your user in the backend).

3
  • This was the only secure solution I could come up with for API Gateway websockets. Slack does something similar with their RTM API and they have a 30 second timeout.
    – andrhamm
    Jul 19, 2019 at 0:42
  • 2
    Note that if you're creating a websocket connection from node-js (as opposed to the browser), sending an authorization header is possible. See here: github.com/apollographql/apollo-client/issues/…
    – Venryx
    Jul 19, 2021 at 8:10
  • so instead of adding the ability to set headers, you're meant to duplicate your entire auth stack just to authenticate a websocket? Am I missing something?
    – Alita
    Nov 25 at 8:07
41

HTTP Authorization header problem can be addressed with the following:

var ws = new WebSocket("ws://username:[email protected]/service");

Then, a proper Basic Authorization HTTP header will be set with the provided username and password. If you need Basic Authorization, then you're all set.


I want to use Bearer however, and I resorted to the following trick: I connect to the server as follows:

var ws = new WebSocket("ws://[email protected]/service");

And when my code at the server side receives Basic Authorization header with non-empty username and empty password, then it interprets the username as a token.

11
  • 15
    I am trying the solution suggested by you. But I am not able to see the Authorization header being added to my request. I have tried it using different browsers e.g. Chrome V56, Firefox V51.0 I am running my server on my localhost. so the websocket url is "ws://myusername:mypassword@localhost:8080/mywebsocket". Any idea what might be wrong? Thanks Mar 11, 2017 at 21:15
  • 6
    Is it safe to transfer token through url? May 4, 2017 at 18:02
  • 9
    I agree with @LearnToLive - I used this with wss (e.g. wss://user:[email protected]/ws) and got no Authorization header on the server side (using Chrome version 60)
    – user9645
    Aug 4, 2017 at 13:59
  • 6
    I have the same issue as @LearnToLive and @user9645; neither chrome nor firefox are adding the authorization header when the URI is in the wss://user:pass@host format. Is this not supported by browsers, or is something going wrong with the handshake? Feb 2, 2018 at 20:42
  • 14
    The use of these urls http://username:[email protected] is depreciated. developer.mozilla.org/en-US/docs/Web/HTTP/Authentication. Maybe thats the reason it does not work with websockets either!
    – Dachstein
    Aug 19, 2018 at 18:14
31

You cannot add headers but, if you just need to pass values to the server at the moment of the connection, you can specify a query string part on the url:

var ws = new WebSocket("ws://example.com/service?key1=value1&key2=value2");

That URL is valid but - of course - you'll need to modify your server code to parse it.

6
  • 32
    need to be careful with this solution, the query string may be intercepted, logged in proxies etc. so passing sensitive info (users / password / authentication tokens) this way won't be secure enough.
    – Nir
    Apr 23, 2017 at 13:46
  • 8
    @Nir with WSS the querystring should probably be safe May 29, 2017 at 14:49
  • 13
    ws is plain text. Using ws protocol anything can be intercepted. May 30, 2017 at 15:05
  • 1
    @SebastienLorber it is not safe to use query string it is not being encrypted the same applies to HTTPS, but since "ws://..." protocol is used, it really doesn't matter.
    – Lu4
    Sep 20, 2017 at 0:32
  • 16
    @Lu4 the query string is encrypted, but there are a host of other reasons not to add sensitive data as URL query parameters stackoverflow.com/questions/499591/are-https-urls-encrypted/… & blog.httpwatch.com/2009/02/20/… as refs
    – user484261
    Nov 27, 2017 at 19:53
31

You can not send custom header when you want to establish WebSockets connection using JavaScript WebSockets API. You can use Subprotocols headers by using the second WebSocket class constructor:

var ws = new WebSocket("ws://example.com/service", "soap");

and then you can get the Subprotocols headers using Sec-WebSocket-Protocol key on the server.

There is also a limitation, your Subprotocols headers values can not contain a comma (,) !

4
  • 1
    May a Jwt contain a comma?
    – CESCO
    Oct 20, 2016 at 3:52
  • 1
    I don't believe so. JWT consists of three base64-encoded payloads, each separated by a period. I believe this rules out the possibility of a comma.
    – BillyBBone
    Mar 12, 2017 at 2:02
  • 3
    I implemented this and it works - just feels weird. thanks Apr 10, 2017 at 2:14
  • 12
    are you suggesting we use the Sec-WebSocket-Protocol header as alternate to the Authorization header?
    – rrw
    May 14, 2018 at 7:33
23

Here's a quick summary of the situation for the weary traveller stumbling upon this in 2023, and probably for a very long time after that.

Nothing has changed in the 12(!) years since this question was opened. The JavaScript WebSocket API is abandoned by all browser vendors (although the implementations do occasionally get updates), and the new specs (WebSocket Stream and WebTransport) are nowhere close to materialization. What this all means is that WebSockets are still widely used, no replacement for the broken API exists despite it being called "legacy" 7 years ago, and the problems outlined in the question are as annoying as ever, if not more.

The options for dealing with the situation (spoiler, #5 or #6 is what you want):

1. Implement authentication externally

Described in https://devcenter.heroku.com/articles/websocket-security. The client is expected to make an authenticated request to a dedicated end point that will generate and persist a short-lived token that will also be sent to the client. The client then returns this token as a URL param when opening a WebSocket. The server can validate it and accept/reject the protocol upgrade. This requires the server to implement a completely custom and stateful authentication mechanism specifically for WebSockets, which is a bridge too far in many scenarios.

2. Send auth information over WebSocket

You open a WebSocket without authenticating, then you send your auth information over WebSocket prior to doing anything else. This in theory sounds logical (and is advised by the browser vendors), but falls apart given just a cursory thought. The server is made to implement an awkward, highly stateful and entirely custom authentication mechanism that doesn't play well with anything else, on top of either having to maintain a persistent connection with a client who refuses to authenticate, leaving a door wide open for denial of service attacks, or getting into a whole new rabbit whole of enforcing rigorous time outs to prevent malicious behavior.

3. Send auth info (e.g. an access token) via a URL param

Not as terrible as it sounds, as long as SSL is enforced (wss:// not ws://) because WebSocket URLs are special and don't get saved in browser history or similar. On top of that, access tokens are normally short lived, so that also mitigates the danger. But. The server will very likely log the URL anyway at some point. Even if your server application doesn't, the framework or the (cloud) host probably will. Additionally, if you have to pass ID tokens around (like Firebase is wont to do), you might trip up on various URL length limitations as ID tokens get huge.

4. Auth via a good old cookie

Don't. WebSockets are not subject to same-origin policy (because apparently every little thing about WebSockets has to be awful) and allowing cookies would leave you wide open to XSRF attacks. Fixing this would be more difficult than taking any other approach from this list, so it is simply not even worth considering.

5. Smuggle access tokens inside Sec-WebSocket-Protocol

Since the only header a browser will let you control is Sec-WebSocket-Protocol, you can abuse it to emulate any other header. Interestingly (or rather comically), this is what Kubernetes is doing. In short, you append whatever you need for authentication as an extra supported subprotocol inside Sec-WebSocket-Protocol:

var ws = new WebSocket("ws://example.com/path", ["realProtocol", "yourAccessTokenOrSimilar"]);

Then, on the server, you add some sort of middleware that transforms the request back to its saner form before passing it further into the system. Terrible, yes, but so far the best solution. No tokens in the URL, no custom authentication save for the little middleware, no extra state on the server needed.

6. Switch to SSE (or RSocket?), if applicable

For a good number of cases, SSE might be a decent replacement. The browser EventSource API is as horribly broken as WebSocket (it can't send anything but GET requests, can't send headers either despite being regular HTTP), but! it can be easily replaced by fetch which is, for a change, a saner API. This approach works well as an alternative to WebSocket in e.g. GraphQL subscriptions, or really anywhere where full duplex isn't mandatory. And that likely covers most scenarios. RSocket could theoretically also be an option, but seeing how it's implemented via WebSockets in the browser, I don't think it actually resolves anything, but I didn't look into it deep enough to say with absolute certainty.

7
  • 2
    Thank you for this answer! It saved me a lot of research in 2023! Sep 27 at 17:43
  • @EmmaAlecrim Happy to hear that! ☺️
    – kaqqao
    Sep 27 at 19:11
  • Do you mind offering more details on how to setup the middleware for #5 (smuggling)? Specifically, is there an easy way to setup some kind of middleware for my nginx ingress controller in a kubernetes cluster?
    – Alita
    Nov 25 at 8:19
  • @Alita I've never done it in nginx (I did it in the application itself), but I imagine it should be achievable with a map directive and add_header (or proxy_set_header). Something like: map $http_sec_websocket_protocol $extracted_token { "~realProtocol(?<t>.*)" $t; } to get the token out of the subprotocol header, and then add_header Authorization "Bearer $extracted_token"; to recreate the usual auth header. I've never tried any of this, so take it as a guideline more than a definitive answer. Not sure if there's anything Kubernetes specific to worry about.
    – kaqqao
    Nov 26 at 11:13
  • 1
    by the way, in case any ever needs a simpler solution. You can use the auth-url in combination with the auth-response-headers to accomplish this (for reference: medium.com/@ankit.wal/…). Precisely, you can use the auth-url to hit a service which extracts the relevant header, then returns that header in the response. Then use the auth-response-headers to apply that header to the request in the Ingress. I would have used this, but my goal was associated with session affinity and this didnt' work
    – Alita
    Nov 26 at 11:26
22

For those still struggling in 2021, Node JS global web sockets class has an additional options field in the constructor. if you go to the implementation of the the WebSockets class, you will find this variable declaration. You can see it accepts three params url, which is required, protocols(optional), which is either a string, an array of strings or null. Then a third param which is options. our interest, an object and (still optional). see ...

declare var WebSocket: {
    prototype: WebSocket;
    new (
        uri: string,
        protocols?: string | string[] | null,
        options?: {
            headers: { [headerName: string]: string };
            [optionName: string]: any;
        } | null,
    ): WebSocket;
    readonly CLOSED: number;
    readonly CLOSING: number;
    readonly CONNECTING: number;
    readonly OPEN: number;
};

If you are using a Node Js library like react , react-native. here is an example of how you can do it.

 const ws = new WebSocket(WEB_SOCKETS_URL, null, {
    headers: {
      ['Set-Cookie']: cookie,
    },
  });

Notice for the protocols I have passed null. If you are using jwt, you can pass the Authorisation header with Bearer + token

Disclaimer, this might not be supported by all browsers outside the box, from the MDN web docs you can see only two params are documented. see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket#syntax

6

Totally hacked it like this, thanks to kanaka's answer.

Client:

var ws = new WebSocket(
    'ws://localhost:8080/connect/' + this.state.room.id, 
    store('token') || cookie('token') 
);

Server (using Koa2 in this example, but should be similar wherever):

var url = ctx.websocket.upgradeReq.url; // can use to get url/query params
var authToken = ctx.websocket.upgradeReq.headers['sec-websocket-protocol'];
// Can then decode the auth token and do any session/user stuff...
1
  • 7
    Doesn't this just pass your token in the section where your client is supposed to request one or more specific protocols? I can get this working, no problem too, but I decided not to do this and rather do what Motes suggested and block until the auth token is sent on the onOpen(). Overloading the protocol request header seems wrong to me, and as my API is for public consumption, I think it is going to be kinda confusing for consumers of my API.
    – Jay
    Jun 27, 2017 at 9:57
5

In my situation (Azure Time Series Insights wss://)

Using the ReconnectingWebsocket wrapper and was able to achieve adding headers with a simple solution:

socket.onopen = function(e) {
    socket.send(payload);
};

Where payload in this case is:

{
  "headers": {
    "Authorization": "Bearer TOKEN",
    "x-ms-client-request-id": "CLIENT_ID"
}, 
"content": {
  "searchSpan": {
    "from": "UTCDATETIME",
    "to": "UTCDATETIME"
  },
"top": {
  "sort": [
    {
      "input": {"builtInProperty": "$ts"},
      "order": "Asc"
    }], 
"count": 1000
}}}
2
  • It doesn't look like generic way to pass custom headers as don't see an option in their API. Is it a generic way or works only with Azure and some server side configuration?
    – Naga Kiran
    Apr 18, 2021 at 16:38
  • This might be a decent enough work around for some, but it's worth noting that this will add a lot of IO for particularly chatty use-cases (the headers are sent every request). Mar 21, 2022 at 19:54
4

The recommended way to do this is through URL query parameters

// authorization: Basic abc123
// content-type: application/json
let ws = new WebSocket(
  "ws://example.com/service?authorization=basic%20abc123&content-type=application%2Fjson"
);

This is considered a safe best-practice because:

2

to all future debugger - until today i.e 15-07-21

Browser also don't support sending customer headers to the server, so any such code

    import * as sock from 'websocket'
    const headers = {
        Authorization: "bearer " + token
    };
    console.log(headers);

    const wsclient = new sock.w3cwebsocket(
        'wss://' + 'myserver.com' + '/api/ws',
        '',
        '',
        headers,
        null
    );

This is not going to work in browser. The reason behind that is browser native Websocket constructor does not accept headers.

You can easily get misguided because w3cwebsocket contractor accepts headers as i have shown above. This works in node.js however.

1

I've tried these two approaches and neither worked, hopefully this will save you time:

  1. Implement websockets using fetch and streams api Is it possible to implement websockets in Javascript with Streams api?
  2. Use WebAssembly instead of javascript Feasibility of using WebAssembly to implement a WebSockets Client
0

What I have found works best is to send your jwt to the server just like a regular message. Have the server listening for this message and verify at that point. If valid add it to your stored list of connections. Otherwise send back a message saying it was invalid and close the connection. Here is the client side code. For context the backend is a nestjs server using Websockets.

  socket.send(
      JSON.stringify({
        event: 'auth',
        data: jwt
      })
    );
0

Client Side: No

Server Side: Yes

All you need to do is attach the header to the websocket after auth on the server. All future communication with that websocket will have that auth token.

Server Environment: Bun JS / Elysia

  • This should translate over to node / express, I just have not done it there.

Example:

const app = new Elysia({
  websocket: {
    idleTimeout: 180
  }
});

app.ws("/ws", {
  message: async (ws, message) => {
    // message = { action: 'LOGIN', payload: { username: 'bob', password: 'iAmB0B' }}
    if(message.action === 'LOGIN') {
      // Do auth stuff 
      const token = await callAuth(message.payload);
      if(token) {
        ws.data.headers['authorization'] = `Bearer ${token}`;
      }
    } else {
      // Verify Auth - All future calls with this socket will have this auth.
      const auth = ws.data.headers['authorization']; // `Bearer ${token}`
    }
  }
});

References:

Bun JS Websockets: https://bun.sh/docs/api/websockets

Elysia JS Websockets: https://elysiajs.com/patterns/websocket.html

-2

My case:

  • I want to connect to a production WS server a www.mycompany.com/api/ws...
  • using real credentials (a session cookie)...
  • from a local page (localhost:8000).

Setting document.cookie = "sessionid=foobar;path=/" won't help as domains don't match.

The solution:

Add 127.0.0.1 wsdev.company.com to /etc/hosts.

This way your browser will use cookies from mycompany.com when connecting to www.mycompany.com/api/ws as you are connecting from a valid subdomain wsdev.company.com.

-5

You can pass the headers as a key-value in the third parameter (options) inside an object. Example with Authorization token. Left the protocol (second parameter) as null


ws = new WebSocket(‘ws://localhost’, null, { headers: { Authorization: token }})

Edit: Seems that this approach only works with nodejs library not with standard browser implementation. Leaving it because it might be useful to some people.

3
  • 3
    Had my hopes up for a sec. There doesn't appear to be an overload taking a 3rd param in WebSocket ctor.
    – Levitikon
    Dec 18, 2019 at 14:18
  • 1
    Got the idea from wscat code. github.com/websockets/wscat/blob/master/bin/wscat line 261 wich uses the ws package. Thought this was an standard usage.
    – Nodens
    Jan 16, 2020 at 11:29
  • 3
    This doesn't work for client side and at the server this answer seems irrelevant.
    – iwaduarte
    May 7, 2021 at 22:25
-6

Technically, you will be sending these headers through the connect function before the protocol upgrade phase. This worked for me in a nodejs project:

var WebSocketClient = require('websocket').client;
var ws = new WebSocketClient();
ws.connect(url, '', headers);
5
  • 5
    This is for the websocket client in npm (for node). npmjs.com/package/websocket Overall this would be exactly what I am looking for, but in the browser.
    – arnuschky
    Aug 16, 2017 at 22:50
  • 3
    It's downvoted because this headers parameter in on the WebSocket protocol layer, and the question is about HTTP headers.
    – Toilal
    Nov 30, 2017 at 13:49
  • "headers should be either null or an object specifying additional arbitrary HTTP request headers to send along with the request." from WebSocketClient.md; therefore, the headers here is HTTP layer.
    – momocow
    Oct 28, 2018 at 7:41
  • Also, anyone who wants to provide custom headers should keep in mind the function signature of the connect method, described as connect(requestUrl, requestedProtocols, [[[origin], headers], requestOptions]), i.e. the headers should be provided along with requestOptions, for example, ws.connect(url, '', headers, null). Only the origin string can be ignored in this case.
    – momocow
    Oct 28, 2018 at 7:47
  • This solution only works for the ws nodejs client
    – alxpez
    Sep 29, 2021 at 10:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.