How to Secure WebSocket Connections with JWT Authentication
This guide explains the security challenges of WebSocket, outlines a step‑by‑step JWT authentication flow, and presents three practical token‑passing techniques—including URL parameters, post‑connection messages, and sub‑protocols—while emphasizing the use of wss:// and safe token storage.
WebSocket does not inherently solve security issues; developers must implement their own protections.
Authentication Steps
Using JWT for authentication is common; the token can be passed via the WebSocket URL.
The general process is:
User login : User logs in via HTTP with username and password.
Generate JWT : Server validates credentials and creates a signed JWT containing identity and claims.
Send JWT : Server returns the token to the client.
Client stores JWT : Client stores the token securely (e.g., LocalStorage, SessionStorage, or cookies).
Establish WebSocket connection : Client opens a WebSocket and appends the token as a query parameter, e.g.
ws://wss.tinywan.com/socket?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...Server validates JWT : Server extracts the token from the URL, verifies signature, expiration, and required claims.
Connection established : If validation succeeds, the server accepts the connection; otherwise it rejects it.
Subsequent communication : After the connection is open, client and server can exchange messages; the JWT may be sent with each message for continuous verification.
Always transmit the JWT over a secure WebSocket (wss://) to prevent man‑in‑the‑middle attacks, and never embed sensitive data in the token because it can be decoded.
Token Transmission Methods
Because the WebSocket API does not allow custom HTTP headers during the handshake, tokens must be passed by alternative means.
1. Token in URL query string
This method is simple but exposes the token in the URL.
var ws = new WebSocket("ws://wss.tinywan.com?authorization=" + ACCESS_TOKEN);
ws.onopen = function(evt) {
ws.send("认证授权和实现思路");
};2. Send token after TCP connection is established
var ws = new WebSocket("ws://wss.tinywan.com");
ws.addEventListener('open', (event) => {
ws.send('Authorization: Bearer ' + ACCESS_TOKEN);
});3. Use WebSocket sub‑protocol (Sec‑WebSocket‑Protocol)
Pass the token as a sub‑protocol; the server must support and process it.
const access_token = localStorage.getItem('access_token');
var ws = new WebSocket("ws://wss.tinywan.com", [access_token]);Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
