简体   繁体   English

快速中间件中的Node.js JWT刷新令牌

[英]Node.js JWT refresh token in express middleware

I'm trying to configure a token refresh method in my express middleware in wich the token is validate at every request to the api. 我正在尝试在我的表达中间件中配置令牌刷新方法,以使令牌在对api的每个请求中均有效。 I will check if the token expired and if so, I will sign a new token with new exp date. 我将检查令牌是否过期,如果已过期,我将使用新的到期日签署新令牌。 The problem is that I have to send the token again, but doing thatI lose the original request to send the token with the response and the api not continue to the destination endpoint. 问题是我必须再次发送令牌,但是这样做我失去了发送带有响应的令牌的原始请求,并且api无法继续到达目标端点。 How I can send back the new refreshed token and continue with the request? 如何发送回新的刷新令牌并继续请求?

My express middleware to check the token: 我的快速中间件检查令牌:

apiRouter.use(function(req, res, next) {
      var token = req.body.token || req.query.token || req.headers['x-access-token'];
      if (token) {
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {
          if (err) {
            //Here I can check if the received token in the request expired
            if(err.name == "TokenExpiredError"){
                var refreshedToken = jwt.sign({
                    success: true,
                    }, app.get('superSecret'), {
                        expiresIn: '5m'
                    });
                //Here need to send the new token back to the client and continue with the request
                //but if I use return res.... the request don't continue to next()
                next();
              }else if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });
              }         
          } else {
            //If no error with the token, continue 
            next();
          };
        });
      } else {
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
      }
    });

I dont' know if its the best aproach to this. 我不知道这是否是最好的方法。

Thanks you. 谢谢。

You can not send a response to the client two times for single request, so better way will be sent an access token with the actual API response. 对于单个请求,您不能两次向客户端发送响应,因此更好的方式是将发送带有实际API响应的访问令牌。

apiRouter.use(function(req, res, next) {
      var token = req.body.token || req.query.token || req.headers['x-access-token'];
      if (token) {
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {
          if (err) {
            //Here I can check if the received token in the request expired
            if(err.name == "TokenExpiredError"){
                var refreshedToken = jwt.sign({
                    success: true,
                    }, app.get('superSecret'), {
                        expiresIn: '5m'
                    });
                request.apiToken = refreshedToken;
                next();
              }else if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });
              }         
          } else {
            //If no error with the token, continue 
            request.apiToken = token;
            next();
          };
        });
      } else {
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
      }
    });

then when you send a response then send a response with the token, that you can get with request.apiToken. 然后,当您发送响应时,然后发送带有令牌的响应,您可以通过request.apiToken获得该令牌。

but a better strategy is to provide a client refresh token and let the client make a request to get refreshed token. 但更好的策略是提供客户端刷新令牌,并让客户端发出请求以获取刷新令牌。

You can read more about that here 您可以在此处了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM