Back to articles
WebSocket Authentication: Securing Real-Time Connections

WebSocket Authentication: Securing Real-Time Connections

via Dev.to WebdevYoung Gao

WebSocket Authentication: Securing Real-Time Connections Your WebSocket server accepts any connection. Anyone can subscribe to private channels. Here is how to authenticate WebSocket connections properly. Token-Based Authentication import { WebSocketServer } from " ws " ; import jwt from " jsonwebtoken " ; const wss = new WebSocketServer ({ noServer : true }); server . on ( " upgrade " , ( req , socket , head ) => { // Extract token from query string or header const url = new URL ( req . url , " http://localhost " ); const token = url . searchParams . get ( " token " ); if ( \ ! token ) { socket . write ( " HTTP/1.1 401 Unauthorized " ); socket . destroy (); return ; } try { const user = jwt . verify ( token , process . env . JWT_SECRET ); wss . handleUpgrade ( req , socket , head , ( ws ) => { ws . user = user ; wss . emit ( " connection " , ws , req ); }); } catch { socket . write ( " HTTP/1.1 401 Unauthorized " ); socket . destroy (); } }); Channel Authorization wss . on ( " connect

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
6 views

Related Articles