【发布时间】:2020-10-17 23:38:17
【问题描述】:
我的问题的症结在于 PassportJS 似乎正在验证一个 JWT,由于当前时间超过了 exp 参数,该 JWT 应该是无效的。
我已经提供了相关的代码 sn-ps 和我认为应该发生的事情的解释(虽然它显然不是!!)
代码
// In server.js
// ...
const passport = require("passport");
// ...
require("./config/passport")(passport);
app.use(passport.initialize());
// ...
// In token.js (used to issue JWT)
const jsonwebtoken = require("jsonwebtoken");
// ...
const issueJWT = (user) => {
const _id = user._id;
const expiresIn = 30000; // 30s for testing purposes
const payload = {
sub: _id,
iat: Date.now(),
};
const signedToken = jsonwebtoken.sign(payload, PRIV_KEY, {
expiresIn: expiresIn,
algorithm: "RS256",
});
return {
token: "Bearer " + signedToken,
expires: expiresIn,
};
};
// In passport.js
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
// ...
const options = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: PUB_KEY,
algorithms: ["RS256"],
};
module.exports = (passport) => {
passport.use(
new JwtStrategy(options, (jwt_payload, done) => {
User.findOne({ _id: jwt_payload.sub }, (err, user) => {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
};
// In routes.js
// ...
const passport = require("passport");
const { authenticateWithAccessToken } = require("../controllers/usersController");
// ...
router
.route("/authenticate-with-access-token")
.get(
passport.authenticate("jwt", { session: false }),
authenticateWithAccessToken
);
// In usersController.js
exports.authenticateWithAccessToken = async (req, res, next) => {
try {
const user = req.user;
res.status(200).json({
success: true,
name: user.name,
email: user.email,
});
} catch (err) {
next(err);
}
};
样本负载
{
alg: "RS256",
typ: "JWT"
}.
{
sub: "5eec9f1c4a416c1e50fc0a8e", // user._id
iat: 1593258411458, // 2020-06-27 11:46:51
exp: 1593258441458 // 2020-06-27 11:47:21
}.
[signature]
我预计会发生什么
- 客户端向 /authenticate-with-access-token 发送 GET 请求,并在 auth 标头中使用 Bearer 令牌 (JWT)
- PassportJS(通过
jsonwebtoken.verify())尝试验证 JWT,但发现Date.now()超过了 JWT 的有效期 - PassportJS 引发错误,使用 401 Unauthorized 响应解决请求
发生了什么
- 客户端向 /authenticate-with-access-token 发送 GET 请求,并在 auth 标头中使用 Bearer 令牌 (JWT)
- PassportJS 将用户对象传入请求体并调用
next() - 最后一块中间件运行,使用 200 OK 响应解析请求,并通过 JSON 正文传回用户详细信息
我确定我遗漏了一些明显的东西,但对于我的生活,我无法弄清楚发生了什么。提前感谢您的帮助!
【问题讨论】:
标签: javascript jwt passport.js