简体   繁体   中英

Session object storing JWT + handling refresh tokens in node.js backend

I am building my application using Angular and node.js (express) and I am using JWT for authentication and authorization. Currently, I am storing JWT in session object on server in memory (req.session.jwt = user.generateToken()) and also, I am sending refresh token in HttpOnly cookie to the client.

When JWT expires, I want server to give me new JWT, if refresh token from cookie is equal to the refresh token in database - asociated with user.

I tried to implement refresh token logic in my auth middleware in the catch block, but it did not work.

(If token validation failed, then compare RF token from cookie to RF in database, if true, set new JWT and run the routehandler.)

module.exports = function(req, res, next) {
  const token = req.session.jwt;

  if (!token) return res.status(401).send("Access denied.");

  try {
    const decoded = jwt.verify(token, config.get("jwtPrivateKey"));
    req.user = decoded;
    next();
  } catch (ex) {
    (async () => {
      let user = await User.findOne({ username: req.session.username });
      if (!user) return res.status(500).send("Invalid session");

      if (user.refreshToken === req.signedCookies.refreshToken) {
        req.session.jwt = user.generateToken();
        next();
      } else {
        return res.status(401).send("Invalid session");
      }
    })();
  }
};

I had implemented this refresh token logic, when I was storing token and refresh token in localstorage on client, but this was not great implementation, so I tried to make it like this. I had token.interceptor in my Angular part of the project - from this tutorial ( https://angular-academy.com/angular-jwt/#refresh-token )

Here is my github repo of the backend https://github.com/TenPetr/dashboard_backend

If you have any idea, how to implement this logic, please let me know.

Thanks for your advices.

When you generate a new JWT token, as the request is going to continue to next middleware step, probably you will need to set the user, same as you do when the jwt is correct. Something like this, try it, and let me know if it helps:

if (user.refreshToken === req.signedCookies.refreshToken) {
  req.session.jwt = user.generateToken();
  const decoded = jwt.verify(req.session.jwt, config.get("jwtPrivateKey"));
  req.user = decoded;
  next();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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