Home > Enterprise >  Node express Json Web Token- how to handle invalid token
Node express Json Web Token- how to handle invalid token

Time:12-25

const token = req.headers[process.env.AUTH_KEY_NAME];
    if (!token) return res.send("No token provided").status(401);

    try {
      const user = jwt.verify(token, process.env.JWT_KEY);
      return res.status(200).json(user);
    } catch (e) {
      return res.send(e).status(401);
    }
  },

This is code I use to handle token validation. There are 3 possibilities: no token provided, wrong token provided, correct token. Everything is called when it should correctly hovewer when the token is incorrect i get the error in console 'JsonWebTokenError: invalid token', that is correct but it also crashes the app. How do I prevent from crashing ? Here is other code I found that also crashes app with invalid token

const user = jwt.verify(token, process.env.JWT_KEY, (err, payload) => {
      if (err) {
        return res.send(err).status(401);
      }
    });
    return res.status(200).json(user);

CodePudding user response:

i use a middleware (auth.middleware.ts) for token validation, which looks like this.

// auth.middleware.ts
import jwt from 'jsonwebtoken';

export default function (req, res, next) {
  try {
    const token = req.headers.authorization.split(' ')[1];
    const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
    // add userData object to request
    req.userData = {
      email: decodedToken.email,
      userId: decodedToken.userId,
      username: decodedToken.username,
      role: decodedToken.role,
    };
    next();
  } catch (error) {
    return res.status(401).json({
      message: 'not authenticated',
    });
  }
}

then i use the middleware function in my routes like this.

// cycle.routes.ts
import express from 'express';
import authMiddleware from '../middleware/auth.middleware';
import CycleController from './cycle.controller';

class CycleRoutes {
  router = express.Router();
  cycleController = CycleController;

  constructor() {
    this.configureRoutes();
  }

  configureRoutes() {
    this.router.post('/cycle/start', authMiddleware, this.cycleController.start);
  }
}

export default new CycleRoutes().router;

for reference I will link you a repo where you can check how i implemented this middleware as seeing example code helps me alot when learning new things.

https://gitlab.com/fiehra/sumaho

CodePudding user response:

Use the callback function to prevent the app from crashing.

var tokenData;
jwt.verify(token, process.env.JWT_KEY, (err, data) => {
  data && (tokenData = data);
});
if (!tokenData) {
  throw new Error("==> Token expired");
}

I think this will work.

  • Related