jwt中过期时如何刷新令牌 [英] how to refresh token when expired in jwt

查看:2416
本文介绍了jwt中过期时如何刷新令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的项目中实施JWT.我实现了jwt,并给了它1分钟的到期时间.从api端生成的jwt在登录期间,令牌和到期详细信息在结果中发送并存储在本地存储中.如何从API端刷新过期的令牌,然后将其再次发送回客户端,以便可以将其存储在本地存储中,并使用拦截器为每次调用发送?

I am implementing JWT in my project. I implemented jwt and gave it an expiration time of 1 minute. The jwt that is generated from the api side is during login and the token and expiration details are sent in the result and are stored in local storage. How can I refresh the expired token from API side and send it back again to the client so that it can be stored in local storage and sent for every call using interceptor?

这就是我创建jwt并赋予到期时间的方式

this is how I created jwt and gave expiration time

// let us suppose this is my input
tokenObject = { User: { username: name, pwd: pwd } };
//creating a jwt here
jwt.sign({ tokenObject }, "secretkey", { expiresIn: "60s" }, (err, token) => {
  res.json({
    token
  });
});

此后,我正在验证结果中的令牌并将其发送到客户端. 一分钟后,我如何重新生成令牌? 请帮忙,让我知道路,并告诉我我做错了什么.谢谢!

After this, I'm verifying the token in the result and sending it in result to the client. After a minute how do I regenerate the token? Please help and let me know the way and tell me if I am doing something wrong . Thanks!!

推荐答案

您需要添加一个函数或中间件,以检查JWT是否有效.您可以使用JWT库的verify方法:

You need to add a function or middleware that will check that the JWT is valid or not. You can use the verify method of JWT library:

jwt.verify(token, 'secretKey', function (err, decoded) {
  if (err) {
    if (err.name === 'TokenExpiredError') {
       //create a new token and send the same way you created initially
    }
  }
});

这篇关于jwt中过期时如何刷新令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆