我如何理解基于jwt的身份验证应该有效:
401 Unauthorized
回复。我想如何实现它:
如果上面的描述是正确的,那么将刷新令牌作为签名的jwt令牌的有效负载是否有任何问题?:
function signToken(id, role, refresh_token) {
return jwt.sign(
{
_id: id,
role: role,
refresh_token: refresh_token
},
config.jwt.secret,
{
expiresIn: 60*60*24, // expires in 1 day
}
);
}
以这种方式总是在每个请求中发送刷新令牌和jwt令牌?通过执行此操作,客户端不必使用刷新令牌发送单独的请求以获取新的jwt令牌:
Auth中间件看起来像这样:
function authenticate (req, res, next) {
// Token attached to request in previous middleware
let token = req.token
// verifies secret and checks exp
jwt.verify(token, config.jwt.secret, {ignoreExpiration: true}, (err, decoded) => {
if (err) {
return res.status(500).json({ success: false, message: err.message });
}
//Expired token, try to refresh
if(decoded.exp*1000 < Date.now()){
User.findById(decoded._id, (err, user) => {
if(err) {return res.send(err);}
if(!user){
return res.status(500).json({ success: false, message: 'Token owner not found.' });
}
//if refresh token found, and not expired, refresh expiry time
let isValidToken = _(user.refresh_tokens)
.filter( (token) => {return token.expires>Date.now()} )
.any({token: decoded.refresh_token});
if(!isValidToken){
req.user = {role: 'Guest'};
return next();
}
let newToken = signToken(decoded._id, decoded.role, decoded.refresh_token);
req.token = newToken;
req.user = decoded;
return next();
})
} else {
// if everything is good, save to request for use in other routes
req.user = decoded;
return next();
}
});
}