WebSocket
Securing a WebSocket connection
Here’s how to secure a WebSocket connection. We’ll review a minimal real-time chat example. The server simply echoes back what you send.
This is what we’re building:
You can test it live here:
This example uses Node.js + Hono. We don’t provide a framework-by-framework (or runtime-by-runtime) guide yet. But you should be able to adapt the same approach to your environment.
Key takeaways:
Authentication happens when handling the HTTP upgrade request.
Browsers don’t let you attach custom headers to a WebSocket upgrade request. Use the
protocolsparameter to carry the access token, then read it server-side fromSec-WebSocket-Protocol.WebSocket upgrades are out of scope for DPoP. There’s no RFC-defined way to send and validate a DPoP proof on the upgrade request. In practice, you must skip DPoP proof validation for the upgrade (
rejectIfAccessTokenDPoPBound: false). If you need DPoP-grade guarantees on the socket, add an application-level handshake (off-channel).
Server-side code
Auth utilities:
Client-side code
The source of the React component that consumes getChat is here.
Was this helpful?