当节点js中的令牌即将到期时,生成刷新令牌。

时间:2020-03-28 20:05:30

标签: node.js express

我正在使用nodejs,express和mongodb构建rest api。成功登录用户后,我将在响应中返回jsonwebtoken到客户端,并且.env文件中令牌的expiredIn设置为'30m'。

当旧令牌即将过期时,如何生成新的刷新令牌。就像它已经过去了90%的时间段一样。那时我想生成刷新令牌,并将其发送回状态代码为202的用户。旧令牌也将在接下来的60 s内有效,这样,如果客户端在令牌即将发送时发出任何请求,过期,将获得401过期。

当前,我正在使用中间件来验证用户在标头中传递的令牌是否有效,或者令牌是否已全部过期。

exports.validateToken = async (req, res, next) => {
    let authorizationHeaader = req.headers['x-access-token'] || req.headers['authorization'];
    if(authorizationHeaader){
        if (authorizationHeaader.startsWith('Bearer ') || authorizationHeaader.startsWith('bearer ')) {
            // Remove Bearer from string
            var token = authorizationHeaader.slice(7, authorizationHeaader.length);
        }

        if (token) {
            //Passing the token helpers for verification
            global.Helpers.verifyToken(token)
            .then(async jwtDecrept => { 
                req.body.user = jwtDecrept; 
                next();
            }).catch(async err => {
                //if No token not found or token expired will throw error in json response with status 401
                return apiResponse.unauthorizedResponse(res, "Authentication error. Token has required", "");
            });
        } else {
            //if No token found in header will throw error in json response with status 400
            return apiResponse.validationErrorWithData(res, "Authentication error. Token is required", "");
        }
    }else {
        //if no token passed in header will throw error in json response with status 401
        return apiResponse.unauthorizedResponse(res, "Please pass a token in header", "");
    }
}

请提出建议,如何在此中间件中使刷新令牌逻辑生效。

0 个答案:

没有答案
相关问题