此问题在此处已有答案:
Invalidating JSON Web Tokens(33个答案)
10天前关门了。
我目前正在开发一个身份验证系统Mongoose(我是新手),我希望得到一些关于在用户注销时处理JWT令牌过期的方法的反馈。
我已经实现了一种策略,通过比较用户模式中的loggedoutAt
属性和解码后的JWT令牌的iat
(发布于)声明来检查JWT令牌的有效性。如果存在loggedoutAt
时间戳并且大于iat
,则我认为令牌无效并返回401状态。
下面是相关代码的一个片段:
export const auth = asyncHandler(async (req, res, next) => {
// 1-) Check if token exists
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer ")
)
token = req.headers.authorization.split(" ")[1];
if (!token) return next(new ApiError("Please login or sign up", 401));
// 2-) Check if token is not valid or if token is expired
const decodedToken = jwt.verify(token, process.env.JWT_SECRET_KEY);
// 3-) Check if user exists
const user = await User.findById(decodedToken.userId);
if (!user)
return next(new ApiError("Token invalid: User dose not exists", 401));
// 4-) Check if the user has been loggedout with this token
if (user.loggedoutAt) {
const loggedoutAtTimestamp = parseInt(
user.loggedoutAt.getTime() / 1000,
10
);
if (loggedoutAtTimestamp > decodedToken.iat)
return next(new ApiError("Token invalid: User logged out", 401));
}
req.user = user;
next();
});
字符串
这里是logout函数:
export const logout = asyncHandler(async (req, res, next) => {
req.user.loggedoutAt = Date.now();
await req.user.save();
res.status(200).json({ status: "logged out" });
});
型
我的问题:
此策略是否是处理用户注销时令牌失效的合理方法,或者是否有更好的做法我应该考虑?在此实现中是否有潜在的陷阱或改进我应该知道?
我很感激你能提供的任何指导或建议。谢谢!
1条答案
按热度按时间yfjy0ee71#
在您的实现中,如果用户从多个设备登录,则从一个设备注销会自动将用户从其他设备注销。
看看这个问题以及如何使JWT Invalidating JSON Web Tokens无效的答案