Bird
Raised Fist0
Expressframework~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. In Express with WebSocket, when does authentication usually happen for a WebSocket connection?
easy
A. During the HTTP upgrade request before the WebSocket connection is established
B. After the WebSocket connection is fully established
C. Only when sending the first message over WebSocket
D. Authentication is not needed for WebSocket connections

Solution

  1. Step 1: Understand WebSocket handshake

    The WebSocket connection starts with an HTTP upgrade request from client to server.
  2. Step 2: Identify when authentication fits

    Authentication must happen during this upgrade request to allow or deny the connection before it opens.
  3. Final Answer:

    During the HTTP upgrade request before the WebSocket connection is established -> Option A
  4. Quick Check:

    Authentication = HTTP upgrade request [OK]
Hint: Authenticate during upgrade request, not after connection opens [OK]
Common Mistakes:
  • Trying to authenticate after WebSocket connection opens
  • Assuming authentication is unnecessary for WebSocket
  • Authenticating only on first message instead of handshake
2. Which of the following is a correct way to send an authentication token during a WebSocket connection upgrade in Express?
easy
A. Include the token in the WebSocket message after connection opens
B. Send the token as a URL query parameter in the WebSocket URL
C. Send the token in a cookie after the connection is established
D. Send the token in a separate HTTP POST request after connection

Solution

  1. Step 1: Review token sending methods during upgrade

    Tokens can be sent in the URL query string or headers during the HTTP upgrade request.
  2. Step 2: Identify valid option

    Sending the token as a URL query parameter is a common and valid method to authenticate during upgrade.
  3. Final Answer:

    Send the token as a URL query parameter in the WebSocket URL -> Option B
  4. Quick Check:

    Token in URL query = valid during upgrade [OK]
Hint: Use URL query or headers to send token during upgrade [OK]
Common Mistakes:
  • Sending token only after connection opens
  • Using cookies after connection instead of during upgrade
  • Sending token in separate HTTP requests unrelated to upgrade
3. Consider this Express WebSocket upgrade handler snippet:
server.on('upgrade', (req, socket, head) => {
  const token = new URL(req.url, 'http://localhost').searchParams.get('token');
  if (token !== 'secret') {
    socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
    socket.destroy();
    return;
  }
  wss.handleUpgrade(req, socket, head, ws => {
    wss.emit('connection', ws, req);
  });
});
What happens if the token is incorrect?
medium
A. The server ignores the token and accepts the connection
B. The WebSocket connection is established but messages are blocked
C. The server throws an error and crashes
D. The socket connection is closed immediately with 401 Unauthorized

Solution

  1. Step 1: Analyze token check and socket handling

    If the token is not 'secret', the code writes a 401 Unauthorized response and destroys the socket immediately.
  2. Step 2: Understand socket.destroy effect

    Destroying the socket closes the connection before WebSocket handshake completes, rejecting the client.
  3. Final Answer:

    The socket connection is closed immediately with 401 Unauthorized -> Option D
  4. Quick Check:

    Invalid token = socket closed with 401 [OK]
Hint: Invalid token triggers socket destroy with 401 response [OK]
Common Mistakes:
  • Assuming connection is accepted but blocked later
  • Thinking server crashes on invalid token
  • Ignoring socket.destroy effect
4. Given this Express WebSocket upgrade code snippet:
server.on('upgrade', (req, socket, head) => {
  const token = req.headers['sec-websocket-protocol'];
  if (!token || token !== 'valid-token') {
    socket.end();
    return;
  }
  wss.handleUpgrade(req, socket, head, ws => {
    wss.emit('connection', ws, req);
  });
});
What is the main issue with this authentication approach?
medium
A. Using 'sec-websocket-protocol' header for token is incorrect and may cause handshake failure
B. Calling socket.end() instead of socket.destroy() leaks resources
C. Not checking token case-insensitively causes false negatives
D. Emitting 'connection' event before handleUpgrade causes errors

Solution

  1. Step 1: Understand 'sec-websocket-protocol' header usage

    This header is meant for subprotocol negotiation, not for authentication tokens.
  2. Step 2: Recognize handshake impact

    Misusing this header can cause handshake failure or client rejection because clients expect specific values here.
  3. Final Answer:

    Using 'sec-websocket-protocol' header for token is incorrect and may cause handshake failure -> Option A
  4. Quick Check:

    Wrong header for token breaks handshake [OK]
Hint: Use proper headers or URL query for tokens, not subprotocol header [OK]
Common Mistakes:
  • Assuming any header can carry token safely
  • Ignoring WebSocket protocol header purpose
  • Confusing socket.end() and socket.destroy() effects
5. You want to implement token-based authentication for WebSocket connections in Express. Which approach correctly combines token extraction and connection rejection to secure the WebSocket handshake?
server.on('upgrade', (req, socket, head) => {
  // Extract token
  const token = req.headers['authorization']?.split(' ')[1];
  // Verify token
  if (!token || token !== 'my-secret-token') {
    // Reject connection
    socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
    socket.destroy();
    return;
  }
  // Accept connection
  wss.handleUpgrade(req, socket, head, ws => {
    wss.emit('connection', ws, req);
  });
});
hard
A. socket.destroy() should be called after wss.handleUpgrade to reject connection
B. Token extraction from Authorization header is invalid; should use cookies instead
C. This approach correctly extracts token from Authorization header and rejects unauthorized connections during upgrade
D. Rejecting connection by writing 401 is unnecessary; just call socket.end()

Solution

  1. Step 1: Check token extraction method

    The code extracts the token from the Authorization header using standard Bearer token format.
  2. Step 2: Verify rejection method

    If token is invalid, it writes a 401 Unauthorized response and destroys the socket before upgrade completes, properly rejecting connection.
  3. Step 3: Confirm acceptance flow

    If token is valid, it calls handleUpgrade and emits connection event to accept the WebSocket connection.
  4. Final Answer:

    This approach correctly extracts token from Authorization header and rejects unauthorized connections during upgrade -> Option C
  5. Quick Check:

    Authorization header + socket.destroy() = secure upgrade [OK]
Hint: Extract token from Authorization header, reject with 401 and destroy socket [OK]
Common Mistakes:
  • Using cookies instead of headers for token during upgrade
  • Calling socket.destroy() after upgrade instead of before
  • Not sending 401 response before closing socket
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard