Skip to main content

Overview

The WebSocket API uses the same authentication paradigm adopted by the REST API. The credential is checked once, when the connection opens; a connection that fails the check is refused and never reaches status/initialize. Clients that can set request headers send them. A browser cannot, so it carries the credential in the Sec-WebSocket-Protocol header instead.

Using Native Headers

This method is consistent with REST API semantics.

Bearer Token Authentication

In request headers:

API Key-based Authentication

In request headers:

Using Sec-WebSocket-Protocol Header

This syntax is supported to enable clients using the JavaScript WebSockets API, which can offer subprotocols but cannot set headers. The client offers two protocols: a name that says what the credential is, then the credential itself. The credential is encoded as URL-safe base64 over the alphabet [A-Za-z0-9_-]. Padding with = is accepted but not required, and since +, / and = are not legal in a subprotocol, leave the padding off. Anything else, an empty part or a value that does not decode to UTF-8 is refused.

Bearer Token Authentication

In request headers:

API Key-based Authentication

In request headers:

What the server answers

On success, the server echoes the first protocol the client offered in its own Sec-WebSocket-Protocol header (authorization.bearer.base64url or x-api-key.base64url). A browser requires this: it fails the handshake unless the server selects one of the offered protocols. The credential, the second protocol, is never echoed.

Usage in JavaScript

Example web browser code:
btoa accepts only Latin-1 text. Tokens and API keys are ASCII, so this holds for them.

Usage in Python

Example client code with the websockets package, which sends the subprotocols as the header: