0
0
Expressframework~10 mins

Authentication in WebSocket connections in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the WebSocket library.

Express
const WebSocket = require('[1]');
Drag options to blanks, or click blank then click option'
Aexpress
Bws
Chttp
Dsocket.io
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'express' instead of 'ws' for WebSocket import.
Using 'http' which is for HTTP servers, not WebSocket.
2fill in blank
medium

Complete the code to create a WebSocket server attached to an existing HTTP server.

Express
const wss = new WebSocket.Server({ [1]: server });
Drag options to blanks, or click blank then click option'
Aserver
Bapp
ChttpServer
Dport
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'port' which creates a new server instead of attaching.
Using 'app' which is the Express app, not the HTTP server.
3fill in blank
hard

Fix the error in extracting the token from the WebSocket upgrade request headers.

Express
const token = req.headers['[1]'];
Drag options to blanks, or click blank then click option'
Acookie
Bauth-token
Cauthorization
Dsec-websocket-protocol
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'cookie' which is for cookies, not authorization header.
Using 'sec-websocket-protocol' which is unrelated to auth tokens.
4fill in blank
hard

Fill both blanks to verify the token and accept or reject the WebSocket connection.

Express
wss.on('connection', (ws, req) => {
  const token = req.headers['authorization'];
  if (![1](token)) {
    ws.[2]();
    return;
  }
  // connection accepted
});
Drag options to blanks, or click blank then click option'
AverifyToken
Bclose
Copen
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' instead of 'close' to reject connection.
Using 'open' which is not a method on WebSocket instance.
5fill in blank
hard

Fill all three blanks to extract the token, verify it asynchronously, and accept or reject the connection.

Express
wss.on('connection', async (ws, req) => {
  const token = req.headers['[1]'];
  try {
    const user = await [2](token);
    if (!user) {
      ws.[3]();
      return;
    }
    // connection accepted with user info
  } catch {
    ws.close();
  }
});
Drag options to blanks, or click blank then click option'
Aauthorization
BverifyTokenAsync
Cclose
Dauth
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'auth' instead of 'authorization' header.
Using synchronous verify function instead of async.
Using 'send' instead of 'close' to reject connection.