express-jwt icon indicating copy to clipboard operation
express-jwt copied to clipboard

Catch expired token throwing error

Open george-norris-salesforce opened this issue 6 years ago • 3 comments

Running into the issue where expired token (using credentialsRequired false) is throwing error, and I want to redirect instead. What is the current correct way to handle this?

Same here.

mhaagens avatar Jul 26 '18 13:07 mhaagens

To catch errors in a specific middleware like express-jwt you can wrap it in your own middleware like this, and catch it's errors (in my example I clear the cookie I retrieve the token from):

  app.use((req, res, next) => {
    const handleErrorNext = err => {
      if (err) {
        if (
          err.name === 'UnauthorizedError' &&
          err.inner.name === 'TokenExpiredError'
        ) {
          res.clearCookie('auth0idToken');
          return next();
        }
      }
      next(err);
    };
    const middleware = jwt({
      // ...jwt-express options
    });

    middleware(req, res, handleErrorNext);
  });

hobofan avatar Sep 20 '18 05:09 hobofan

@hobofan this may be a dumb question, but how do you error out from there? Basically I was to say if unauthorized return a 403. If I'm not in the callback I can just throw an HttpException but as soon as I'm in my secondary middleware it doesn't work - it throws for the application but is not handled and the request is simply canceled.

Edit: scratch that! It was as simple as res.status(401).json({});

mcblum avatar May 24 '19 13:05 mcblum