WebSocket auth — verify identity before allowing connections.
1const { WebSocketServer } = require("ws");2const jwt = require("jsonwebtoken");34const wss = new WebSocketServer({ port: 8080 });56wss.on("connection", (ws, req) => {7 // Authenticate on connection8 const token = new URL(req.url, "http://localhost")9 .searchParams.get("token");1011 if (!token) {12 ws.close(1008, "No token provided");13 return;14 }1516 try {17 const user = jwt.verify(token, process.env.JWT_SECRET);18 ws.user = user;19 } catch (err) {20 ws.close(1008, "Invalid token");21 return;22 }2324 ws.on("message", (data) => {25 const message = JSON.parse(data);2627 // Authorize each action28 if (message.type === "admin:delete" && ws.user.role !== "admin") {29 ws.send(JSON.stringify({ error: "Unauthorized" }));30 return;31 }3233 // Handle message34 handleMessage(ws, message);35 });36});
Alternative — verify via HTTP first:
1const server = app.listen(8080);2const wss = new WebSocketServer({ noServer: true });34server.on("upgrade", (req, socket, head) => {5 // Authenticate via session/cookie6 authenticate(req, (err, user) => {7 if (err || !user) {8 socket.destroy();9 return;10 }11 wss.handleUpgrade(req, socket, head, (ws) => {12 ws.user = user;13 wss.emit("connection", ws, req);14 });15 });16});