Last active
February 26, 2018 17:36
-
-
Save acampagnaro/debb2ed19838e4a6b6259e79a5234de2 to your computer and use it in GitHub Desktop.
socketio token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
t doesn't matter if the token was created on another server. You can still verify it if you have the right secret key and algorithm. | |
Implementation with jsonwebtoken module | |
client | |
var token = sessionStorage.token; | |
var socket = io.connect('http://localhost:3000', { | |
query: {token: token} | |
}); | |
Server | |
var io = require('socket.io')(); | |
var jwt = require('jsonwebtoken'); | |
io.use(function(socket, next){ | |
if (socket.handshake.query && socket.handshake.query.token){ | |
jwt.verify(socket.handshake.query.token, 'SECRET_KEY', function(err, decoded) { | |
if(err) return next(new Error('Authentication error')); | |
socket.decoded = decoded; | |
next(); | |
}); | |
} | |
next(new Error('Authentication error')); | |
}) | |
.on('connection', function(socket) { | |
// Connection now authenticated to receive further events | |
socket.on('message', function(message) { | |
io.emit('message', message); | |
}); | |
}); | |
Implementation with socketio-jwt module | |
This module makes the authentication much easier in both client and server side. Just check out their examples. | |
client | |
var token = sessionStorage.token; | |
var socket = io.connect('http://localhost:3000'); | |
socket.on('connect', function (socket) { | |
socket | |
.on('authenticated', function () { | |
//do other things | |
}) | |
.emit('authenticate', {token: token}); //send the jwt | |
}); | |
Server | |
var io = require('socket.io')(); | |
var socketioJwt = require('socketio-jwt'); | |
io.sockets | |
.on('connection', socketioJwt.authorize({ | |
secret: 'SECRET_KEY', | |
timeout: 15000 // 15 seconds to send the authentication message | |
})).on('authenticated', function(socket) { | |
//this socket is authenticated, we are good to handle more events from it. | |
console.log('hello! ' + socket.decoded_token.name); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment