0
0
Expressframework~10 mins

Authentication in WebSocket connections in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Authentication in WebSocket connections
Client sends WebSocket handshake request
Server receives handshake request
Server checks authentication token
Accept connection
Open WebSocket
Exchange messages securely
The client requests a WebSocket connection. The server checks the authentication token during handshake. If valid, connection opens; if not, it rejects.
Execution Sample
Express
const wss = new WebSocket.Server({ noServer: true });
server.on('upgrade', (req, socket, head) => {
  const token = req.headers['sec-websocket-protocol'];
  if (isValidToken(token)) {
    wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req));
  } else {
    socket.destroy();
  }
});
This code checks the token from headers during WebSocket upgrade and accepts or rejects the connection accordingly.
Execution Table
StepActionInputCheckResultConnection State
1Receive upgrade requestHeaders with token 'abc123'Extract tokenToken = 'abc123'No connection yet
2Validate token'abc123'isValidToken('abc123')TrueNo connection yet
3Handle upgradeValid tokenCall handleUpgradeConnection acceptedWebSocket open
4Emit connection eventWebSocket openEmit 'connection'Client connectedWebSocket open
5Receive upgrade requestHeaders with token 'badtoken'Extract tokenToken = 'badtoken'No connection yet
6Validate token'badtoken'isValidToken('badtoken')FalseNo connection yet
7Reject connectionInvalid tokenDestroy socketConnection closedNo connection
💡 Connection accepted only if token is valid; otherwise socket is destroyed and connection rejected.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 6After Step 7
tokenundefined'abc123''abc123''abc123''badtoken''badtoken'
connectionStateNo connectionNo connectionNo connectionWebSocket openNo connectionNo connection
Key Moments - 2 Insights
Why does the server check the token during the 'upgrade' event and not after the WebSocket connection is open?
Because the WebSocket handshake happens during the upgrade request. Checking the token here allows the server to accept or reject the connection before it opens, as shown in steps 2 and 6 of the execution_table.
What happens if the token is invalid?
The server destroys the socket immediately, rejecting the connection. This is shown in step 7 where the connectionState remains 'No connection' and the socket is closed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the connectionState after step 3?
AWebSocket open
BNo connection
CConnection closed
DToken undefined
💡 Hint
Check the 'Connection State' column at step 3 in the execution_table.
At which step does the server reject the connection due to invalid token?
AStep 4
BStep 6
CStep 7
DStep 2
💡 Hint
Look for the step where 'Destroy socket' is the result in the execution_table.
If the token was missing from headers, how would the execution_table change?
AToken would be valid and connection accepted
BToken would be undefined and connection rejected at step 7
CConnection would open without token check
DServer would crash
💡 Hint
Refer to how invalid tokens cause rejection in steps 6 and 7 of the execution_table.
Concept Snapshot
Authentication in WebSocket connections:
- Client sends handshake with token in headers
- Server checks token during 'upgrade' event
- If token valid, server accepts and opens WebSocket
- If invalid, server rejects by closing socket
- Authentication happens before WebSocket connection opens
Full Transcript
When a client wants to open a WebSocket connection, it sends a handshake request to the server. The server listens for this 'upgrade' event and extracts the authentication token from the request headers. It then checks if the token is valid. If yes, the server accepts the connection and opens the WebSocket, allowing message exchange. If the token is invalid or missing, the server immediately closes the connection by destroying the socket. This ensures only authenticated clients can connect. The key moment is that authentication happens during the handshake, before the WebSocket connection is established.