Socket io jwt authentication middleware.
Including verifing middleware for socket.io and signing middleware for express.
const fakeDB = {
leet: { password: '1337' },
};
/**
* Validation example
* @param {*} userdata Decoded data from token
*/
const validation = (userdata) => {
const { username, password } = userdata;
return (
username
&& password
&& fakeDB[username].password === password
);
};
const { socketAuth } = authentication({
secret: 'YourSecretOrPublicKey',
verifyOptions: {
// JWT verify options. see link below
},
}, validation);
// Socket io authentication using the socketAuth middleware
io.use(socketAuth)
.on('connection', (socket) => {
socket.emit('connected', socket.authData);
});
Express example
const { tokenHandler } = authentication({
secret: 'test',
signOptions: {
// JWT signing options. see link below
},
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/token', tokenHandler);
const data = {
username: 'leet',
password: '1337',
};
const res = await fetch(`/api/token`, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
});
const { token } = await res.json();
// Fetch the token like explained above
const token = await fetchToken();
// Connect using the query option token
const socket = client.connect({ query: { token }});
Then store the token in memory for reconnects