我一直在关注这篇文章中关于创建测试 API 应用程序的教程。在文章的结尾,我看到一个提到最好加密 jwt 令牌以增加安全性,所以我也在寻找一种方法来做到这一点。我遇到了这篇文章,它提供了如何使用 RSA 私钥/公钥加密 jwt 令牌的示例。
这就是我卡住的地方。在我使用 /signup 路由成功注册后,我可以使用 /login 路由获取我的令牌。所以我假设这是我在将令牌发送回用户之前使用我的私钥加密令牌的地方?
**公开repo以供测试 - 您只需在 app.js 中提供 mongoDB 连接字符串
我停留在该过程的加密/解密部分,任何帮助表示赞赏。
router.post("/login", async (req, res, next) => {
passport.authenticate("token", async (err, user, info) => {
try {
if (err || !user) {
const error = new Error("An Error occurred");
return next(error);
}
req.login(user, { session: false }, async error => {
if (error) return next(error);
//We don't want to store the sensitive information such as the
//user password in the token so we pick only the email and id
const body = { _id: user._id, email: user.email };
//Sign the JWT token and populate the payload with the user email and id
const token = jwt.sign({ user: body }, PRIV_KEY, { algorithm: 'RS256' });
//Send back the token to the user
return res.json({ token });
});
} catch (error) {
return next(error);
}
})(req, res, next);
});
然后在调用“安全”路由时,我需要根据verify
公钥解密令牌和它吗?
router.get("/profile", (req, res, next) => {
//We'll just send back the user details and the token
jwt.verify(req.query.token, PUB_KEY, { algorithms: ['RS256'] }, function(err, decoded) {
if (err.name === "TokenExpiredError") {
console.log("Whoops, your token has expired!");
}
if (err.name === "JsonWebTokenError") {
console.log("That JWT is malformed!", err); <------ GET ERROR HERE
}
if (err === null) {
console.log("Your JWT was successfully validated!");
}
// Both should be the same
console.log(decoded);
res.json({
message: "You made it to the secure route",
user: req.user
});
});
});