【发布时间】:2020-09-23 01:14:12
【问题描述】:
我已经开发了 JWT 令牌,一切正常。就像生成和验证令牌一样。但问题是我添加了过期时间,但是当我使用旧令牌时,它会将我重定向到我的网络。
jwt.sign(user, process.env.privateKey, { expiresIn: '1h' })
谁能告诉我该怎么做?
我已经搜索了一些人说清除 cookie 的解决方案,如果有人建议我清除 cookie,请告诉我如何清除它们。正确的清除方法。
【问题讨论】:
我已经开发了 JWT 令牌,一切正常。就像生成和验证令牌一样。但问题是我添加了过期时间,但是当我使用旧令牌时,它会将我重定向到我的网络。
jwt.sign(user, process.env.privateKey, { expiresIn: '1h' })
谁能告诉我该怎么做?
我已经搜索了一些人说清除 cookie 的解决方案,如果有人建议我清除 cookie,请告诉我如何清除它们。正确的清除方法。
【问题讨论】:
在中间件中
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。这将检查 JWT 是否已由您签名,并且(对问题更重要)是否已过期。
见:https://www.npmjs.com/package/jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback
【讨论】:
假设您要覆盖符号参数中的默认算法。在这种情况下,将expiresIn 作为另一个完全不同的对象传递。
应该是:
jwt.sign(data, privateKey, { algorithm: 'RS512', expiresIn: expiry })
但不是:
jwt.sign(data, privateKey, { algorithm: 'RS512'}, { expiresIn: expire })
效果不错
【讨论】: