简体   繁体   English

Nodejs jwt 令牌永不过期

[英]Nodejs jwt token never expires

I create jwt token using jsonwebtoken.我使用 jsonwebtoken 创建 jwt 令牌。 I set the token to expire after 5min to check but the token never expires, I always get the iat and exp at the same time like the log below:我将令牌设置为在 5 分钟后过期以进行检查,但令牌永不过期,我总是同时获得iatexp ,如下面的日志:

{ 
   sub: '10001', 
   iat: 1627452909247, 
   exp: 1627452909547 
}
Issue at time: 7/28/2021, 1:15:09 PM | 1627452909247
Expire at time: 7/28/2021, 1:15:09 PM | 1627452909547

And below is my code for the issue and verify token:以下是我的问题代码和验证令牌:

const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const jwt = require('jsonwebtoken');

// Public Key
const pathToPublicKey = path.join( __dirname , ".." ,"/id_rsa_pub.pem");
const publicKey = fs.readFileSync(pathToPublicKey , "utf8");

// Private Key
const pathToPrivateKey = path.join( __dirname , ".." ,"/id_rsa_priv.pem");
const privateKey = fs.readFileSync(pathToPrivateKey , "utf8");

//const expiresIn = '5';
const expiresIn = '5m';
//const expiresIn = '1h';
//const expiresIn = '1d';

const issueJWT = (user) => {

  const user_id = user.user_id;

  const payload = {
    sub: user_id,
    iat: Date.now()
  };

  const jwtOptions = {
    expiresIn: expiresIn,
    algorithm: 'RS256'
  };

  const signedToken = jwt.sign(payload, privateKey, jwtOptions);

  return{
    token: "Bearer " + signedToken,
    expires: expiresIn,
  };

};

const authMiddleware = (req, res, next) => {
  const tokenParts = req.headers.authorization.split(" ");
  
  const jwtOptions = {
    expiresIn: expiresIn,
    algorithms: ['RS256']
  };

  if(tokenParts[0] === "Bearer" && tokenParts[1].match(/\S+\.\S+\.\S+/) !== null)
  {
    try {
      const verification =jwt.verify(tokenParts[1], publicKey, jwtOptions);
      req.jwt = verification ;
      next();
    } catch (error) {
      res.status(401).json({succsess: false , message: 'User Not Authenticated'});
    }
  }
}

module.exports = { issueJWT, authMiddleware};

I tried many ways but still not working.我尝试了很多方法,但仍然无法正常工作。

The timestamps are wrong.时间戳是错误的。 Inspect your token in https://jwt.io and point with the mouse on the timestamp to see how these values are interpreted.https://jwt.io 中检查您的令牌并用鼠标指向时间戳以查看如何解释这些值。

The timestamps in JWT are UNIX timestamps counted in seconds from 01.01.1970 00:00 UTC, not milliseconds (see my answer for more details). JWT 中的时间戳是 UNIX 时间戳,从 01.01.1970 00:00 UTC 算起,以秒为单位,而不是毫秒(有关更多详细信息,请参阅我的回答)。

The way the expiration time exp was set过期时间exp设置方式

const expiresIn = '5m';
const jwtOptions = {
    expiresIn: expiresIn,
    algorithms: ['RS256']
  };
const signedToken = jwt.sign(payload, privateKey, jwtOptions);

is correct and if you delete the line iat: Date.now() you would get a correct token, even with a iat , because that value is automatically included.是正确的,如果您删除行iat: Date.now()您将获得正确的标记,即使使用iat ,因为该值已自动包含在内。

{
  "iat": 1627506023,
  "exp": 1627506323
}

But if the line iat: Date.now() is included, it not only produces a wrong iat but the exp is calculated as iat + 300 (300seconds or 5 minutes) and will also be wrong.但是如果包含了iat: Date.now()行,它不仅会产生错误的iat而且exp计算为iat + 300(300 秒或 5 分钟),而且也会是错误的。

{
  "iat": 1627506191289,
  "exp": 1627506191589
}

The solution is to simply delete the line iat: Date.now() from your code.解决方案是简单地从代码中删除iat: Date.now()行。 If you really need a timestamp in correct format which you want to calculate based on Date.now() you have to divide the value by 1000 and cut of the decimals, eg.:如果您确实需要一个基于Date.now()计算的正确格式的时间戳,您必须将值除以 1000 并Date.now()小数点,例如:

nbf: Math.floor(Date.now()/1000)

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

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