Consider a WebSocket server using Express and a token-based authentication system. What happens if the client tries to connect without sending a valid token in the connection request?
Think about when authentication should happen in the WebSocket handshake process.
Token authentication must happen before upgrading the HTTP connection to WebSocket. If the token is missing or invalid, the server should reject the upgrade request immediately to prevent unauthorized access.
Given an Express WebSocket server, which code correctly retrieves a Bearer token from the Authorization header during the upgrade event?
Remember the format of the Authorization header: 'Bearer <token>'.
The Authorization header usually looks like 'Bearer tokenvalue'. Splitting by space and taking the second part extracts the token correctly. Header keys are case-insensitive but usually lowercase in Node.js.
Review the following Express WebSocket upgrade handler code snippet:
server.on('upgrade', (req, socket, head) => {
const token = req.headers['authorization']?.split(' ')[1];
if (!token) {
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
});Clients without tokens still connect successfully. Why?
server.on('upgrade', (req, socket, head) => { const token = req.headers['authorization']?.split(' ')[1]; if (!token) { socket.destroy(); return; } wss.handleUpgrade(req, socket, head, (ws) => { wss.emit('connection', ws, req); }); });
Look carefully at what the code does with the token after extracting it.
The code only checks if a token exists but does not verify if the token is valid. So any token string, even invalid, allows connection. Proper validation logic is missing.
ws.isAuthenticated after connection if token is valid?In an Express WebSocket server, the following code runs on connection:
wss.on('connection', (ws, req) => {
const token = req.headers['authorization']?.split(' ')[1];
ws.isAuthenticated = verifyToken(token);
});If verifyToken returns true for a valid token, what is the value of ws.isAuthenticated for a client with a valid token?
wss.on('connection', (ws, req) => { const token = req.headers['authorization']?.split(' ')[1]; ws.isAuthenticated = verifyToken(token); });
What does the verifyToken function return for valid tokens?
The code sets ws.isAuthenticated to the result of verifyToken(token). If the token is valid, verifyToken returns true, so ws.isAuthenticated is true.
In Express WebSocket servers, why should authentication be done during the HTTP upgrade request instead of after the WebSocket connection is established?
Think about resource usage and security risks of accepting connections before authentication.
Authenticating during the HTTP upgrade request lets the server reject unauthorized clients early, saving resources and preventing unauthorized access. Waiting until after connection wastes resources and may expose the server to attacks.