简体   繁体   English

socketio-jwt断开过期令牌

[英]socketio-jwt disconnect expired tokens

I am able to authenticate using socketio-jwt and everything is working great. 我能够使用socketio-jwt进行身份验证,并且一切正常。 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. 该库不支持此功能,您可以在所需的每个套接字io事件上验证令牌。

In a Github Issue a contributor answered with this analogy: Github Issue中,一个贡献者用这样的比喻回答:

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. id_token就像您的国家护照一样,都有到期日,您可以输入一个国家/地区,只要您的护照没有过期,并且大多数国家/地区都不会追踪过期时间来追捕您。

You can handle this manually using a socketio middleware for example: 您可以使用socketio中间件手动处理此问题,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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