【发布时间】:2021-10-03 22:12:16
【问题描述】:
我使用 jsonwebtoken 创建 jwt 令牌。我将令牌设置为在 5 分钟后过期以检查但令牌永不过期,我总是同时得到 iat 和 exp,如下面的日志:
{
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
以下是我的问题代码和验证令牌:
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};
试了很多方法还是不行。
【问题讨论】:
标签: javascript node.js express jwt bearer-token