【问题标题】:JWT token does not expires in Node JsJWT 令牌在 Node Js 中不会过期
【发布时间】:2020-09-23 01:14:12
【问题描述】:

我已经开发了 JWT 令牌,一切正常。就像生成和验证令牌一样。但问题是我添加了过期时间,但是当我使用旧令牌时,它会将我重定向到我的网络。

jwt.sign(user, process.env.privateKey, { expiresIn: '1h' })

谁能告诉我该怎么做?

我已经搜索了一些人说清除 cookie 的解决方案,如果有人建议我清除 cookie,请告诉我如何清除它们。正确的清除方法。

【问题讨论】:

    标签: node.js express jwt


    【解决方案1】:

    在中间件中

    const jwt = require('jsonwebtoken');
    const HttpResponse = require('../models/http-response');
    
    
    require('custom-env').env(process.env.NODE_ENV);
    const secret_key=process.env.secret_key;
    
    module.exports = (req, res, next) => {
      if (req.method === 'OPTIONS') {
         return next();
         }
      try {
         const token = req.headers.authorization.split(' ')[1]; // Authorization: 'Bearer 
          TOKEN'
          if (!token) {
            throw new Error('Authentication failed!');
            }
          const decodedToken = jwt.verify(token, secret_key);
          req.userData = { userId: decodedToken.userId };
          next(); 
          } catch (err) {
             const error = new HttpResponse('Authentication failed!', 403);
             return res.json({ response: error });
             }
          };
    

    【讨论】:

    • 我没有找到我的问题的答案,我想知道 jwt 的 expireIn 选项如何在代码中工作
    • 试试这个 token=jwt.sign({user}, process.env.privateKey, { expiresIn: '1h' });
    • 请先阅读问题,我已经使用了它,但 1 小时后仍然可以访问
    • 在我的情况下,它的工作,它会在 1 小时后过期。
    【解决方案2】:

    您需要添加一个中间件来验证 JWT。这将检查 JWT 是否已由您签名,并且(对问题更重要)是否已过期。

    见:https://www.npmjs.com/package/jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback

    【讨论】:

    • 您能否详细说明令牌的具体到期方式?
    • 如果您使用 cookie,您只需取消设置 cookie。如果您不使用 cookie,则不能(您必须放弃请求)
    【解决方案3】:

    假设您要覆盖符号参数中的默认算法。在这种情况下,将expiresIn 作为另一个完全不同的对象传递。

    应该是:

    jwt.sign(data, privateKey, { algorithm: 'RS512', expiresIn: expiry })

    但不是:

    jwt.sign(data, privateKey, { algorithm: 'RS512'}, { expiresIn: expire })

    效果不错

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 2018-08-05
      • 2020-03-01
      • 2021-10-03
      • 2017-03-04
      • 2019-07-04
      • 2014-03-21
      • 2018-03-30
      • 2018-06-19
      相关资源
      最近更新 更多