Securing Socket.IO Connections with JSON Web Tokens (socketio-jwt)
Socket.IO is a popular library that enables real-time, bidirectional, and event-based communication between web clients and servers. When building real-time applications, one of the critical aspects that developers need to address is securing the connections. This is where socketio-jwt comes into play. It provides a simple way to authenticate Socket.IO connections using JSON Web Tokens (JWT).
Getting Started with socketio-jwt
First, we need to install the necessary packages:
npm install socket.io socketio-jwt jsonwebtoken
Generating a JWT
Before we can authenticate connections, we need to generate a JWT. Here is an example:
const jwt = require('jsonwebtoken');
const payload = { userId: 123 };
const secret = 'your-secret-key';
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
console.log(`JWT: ${token}`);
Authenticating Socket.IO Connections
With the token generated, we can now authenticate connections. Below is the code to secure the connections using socketio-jwt:
Server-side Code
const io = require('socket.io')(3000);
const socketioJwt = require('socketio-jwt');
io.use(socketioJwt.authorize({
secret: 'your-secret-key',
handshake: true
}));
io.on('connection', (socket) => {
console.log('User connected:', socket.decoded_token.userId);
socket.on('message', (msg) => {
console.log('Received message:', msg);
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
Client-side Code
const socket = io.connect('http://localhost:3000', {
query: 'token=YOUR_JWT_TOKEN'
});
socket.on('connect', () => {
console.log('Connected to the server');
socket.emit('message', 'Hello, server!');
});
socket.on('disconnect', () => {
console.log('Disconnected from the server');
});
socket.on('error', (err) => {
console.error('Error:', err);
});
Example Application
Let’s build a simple chat application to demonstrate the use of socketio-jwt:
Server
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const socketioJwt = require('socketio-jwt');
const jwt = require('jsonwebtoken');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static('public'));
io.use(socketioJwt.authorize({
secret: 'your-secret-key',
handshake: true
}));
io.on('connection', (socket) => {
console.log('User connected:', socket.decoded_token.userId);
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
app.get('/token', (req, res) => {
const payload = { userId: 'user123' };
const token = jwt.sign(payload, 'your-secret-key', { expiresIn: '1h' });
res.json({ token });
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Client
Socket.IO Chat
This example demonstrates how you can build a secure and functioning real-time chat application using socketio-jwt.
Hash: 3ba5e30f2469390545404ece935920281c770119b90d2dd3adc341dce20f2f1d