Skip to content

Commit d8c9ac7

Browse files
authored
Update secure-websocket-js.md
updated JS code
1 parent 0fb2426 commit d8c9ac7

File tree

1 file changed

+52
-76
lines changed

1 file changed

+52
-76
lines changed

articles/communication-services/how-tos/call-automation/includes/secure-websocket-js.md

Lines changed: 52 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -13,90 +13,66 @@ ms.author: kpunjabi
1313

1414
## Websocket code sample
1515

16-
This sample code demonstrates how to configure OIDC client to validate websocket payload using JWT
16+
This sample code demonstrates how to configure OIDC client to validate websocket payload using JWT.
1717

1818
```JavaScript
19-
import { createServer } from "http";
20-
import WebSocket from "ws";
21-
import { JwksClient } from "jwks-rsa";
22-
import { verify } from "jsonwebtoken";
23-
import url from "url";
24-
25-
const port = 3000;
2619
const audience = "ACS resource ID";
2720
const issuer = "https://acscallautomation.communication.azure.com";
28-
const jwksUri = `${issuer}/calling/keys`;
29-
30-
const server = createServer();
31-
const wss = new WebSocket.Server({ noServer: true });
32-
33-
const jwksClient = new JwksClient({ jwksUri });
34-
35-
function verifyToken(token: string): Promise<any> {
36-
return new Promise((resolve, reject) => {
37-
verify(
38-
token,
39-
(header, cb) => {
40-
jwksClient.getSigningKey(header.kid, (err, key) => {
41-
const signingKey = key?.getPublicKey();
42-
cb(err, signingKey);
43-
});
44-
},
45-
{ audience, issuer, algorithms: ["RS256"] },
46-
(err, decoded) => (err ? reject(err) : resolve(decoded))
47-
);
48-
});
49-
}
50-
51-
// Upgrade HTTP to WebSocket only if token is valid
52-
server.on("upgrade", async (req, socket, head) => {
53-
const tokenHeader = req.headers["authorization"];
54-
const token = tokenHeader?.toString().split(" ")[1];
55-
21+
22+
const jwksClient = new JwksClient({
23+
jwksUri: "https://acscallautomation.communication.azure.com/calling/keys",
24+
});
25+
26+
wss.on("connection", async (ws, req) => {
27+
try {
28+
const authHeader = req.headers?.authorization || "";
29+
const token = authHeader.split(" ")[1];
30+
5631
if (!token) {
57-
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
58-
socket.destroy();
59-
return;
32+
ws.close(1008, "Unauthorized");
33+
return;
6034
}
61-
62-
try {
63-
const decoded = await verifyToken(token);
64-
(req as any).user = decoded;
65-
66-
wss.handleUpgrade(req, socket, head, (ws) => {
67-
wss.emit("connection", ws, req);
68-
});
69-
} catch (e) {
70-
console.error("WebSocket token validation failed:", e);
71-
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
72-
socket.destroy();
73-
}
74-
});
75-
76-
// Handle accepted WebSocket connections
77-
wss.on("connection", async (ws: WebSocket, req) => {
78-
const user = (req as any).user;
79-
console.log("Authenticated WebSocket connection from:", user);
80-
81-
await initWebsocket(ws);
82-
await startConversation();
83-
84-
ws.on("message", async (packetData: ArrayBuffer) => {
35+
36+
verify(
37+
token,
38+
async (header, callback) => {
8539
try {
86-
if (ws.readyState === WebSocket.OPEN) {
87-
await processWebsocketMessageAsync(packetData);
88-
}
40+
const key = await jwksClient.getSigningKey(header.kid);
41+
const signingKey = key.getPublicKey();
42+
callback(null, signingKey);
8943
} catch (err) {
90-
1. console.error("WebSocket message error:", err);
44+
callback(err);
9145
}
92-
});
93-
94-
ws.on("close", () => {
95-
console.log("WebSocket connection closed");
96-
});
97-
});
98-
99-
server.listen(port, () => {
100-
console.log(`WebSocket server running on port ${port}`);
46+
},
47+
{
48+
audience,
49+
issuer,
50+
algorithms: ["RS256"],
51+
},
52+
(err, decoded) => {
53+
if (err) {
54+
console.error("WebSocket authentication failed:", err);
55+
ws.close(1008, "Unauthorized");
56+
return;
57+
}
58+
59+
console.log(
60+
"Authenticated WebSocket connection with decoded JWT payload:",
61+
decoded
62+
);
63+
64+
ws.on("message", async (message) => {
65+
// Process message
66+
});
67+
68+
ws.on("close", () => {
69+
console.log("WebSocket connection closed");
70+
});
71+
}
72+
);
73+
} catch (err) {
74+
console.error("Unexpected error during WebSocket setup:", err);
75+
ws.close(1011, "Internal Server Error"); // 1011 = internal error
76+
}
10177
});
10278
```

0 commit comments

Comments
 (0)