Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socketio-jwt disconnect expired tokens

I am able to authenticate using socketio-jwt and everything is working great. The problem I'm running into is if I set an expiration to a minimum time and let it expire I can continue to emit and receive messages on the connection. As long as I don't refresh the page the connection persists. Once I refresh the connection is disconnected and I am required to reconnect. Is it possible to have the server check for expired tokens and disconnect the connection?

like image 825
Woodsy Avatar asked Sep 09 '16 19:09

Woodsy


1 Answers

The library does not support this feature, you can validate the token on each socket io event that you want.

In a Github Issue a contributor answered with this analogy:

The id_token is like your national passport, both have an expiration, you can enter a country as long as your passport is not expired and most countries will not keep track of expiration to hunt you down.

You can handle this manually using a socketio middleware for example:

const timer = require('long-timeout')

function middleware (socket, next) {
  const decodedToken = socket.user // Assuming the decoded user is save on socket.user

  if (!decodedToken.exp) {
    return next()
  }

  const expiresIn = (decodedToken.exp - Date.now() / 1000) * 1000
  const timeout = timer.setTimeout(() => socket.disconnect(true), expiresIn)

  socket.on('disconnect', () => timer.clearTimeout(timeout))

  return next()
}
like image 117
Nicolas Del Valle Avatar answered Nov 08 '22 00:11

Nicolas Del Valle