简体   繁体   中英

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?

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM