Home > Software design >  Auth jwt middleware returns 500 instead of 401
Auth jwt middleware returns 500 instead of 401

Time:12-28

I made an auth middleware that checks whether access token sent via header is valid.

  • if it expires it should return a 401 error
  • if something is wrong with the token e.g. header is empty, then it should go to catch block and return 500

Every time token expires it goes to the catch block and returns 500.

I just started learning Node/Express, what am i doing wrong?

const jwt = require("jsonwebtoken");

exports.authLogged = async (req, res, next) => {
  try {
    const token = req.get("Token");
    const jwtResp = jwt.verify(token, process.env.JWT_SECRET);
    if (jwtResp?.id) {
      next();
    } else {
      res.status(401).json({
        status: "fail",
        message: "Token expired",
      });
    }
  } catch (e) {
    res.status(500).json({
      status: "fail",
      message: "Fail",
    });
  }
};

CodePudding user response:

It's likely that your verify function is throwing an exception. Instead you may want to add a try catch on that function and catch the specific error type that your function is throwing and return the appropriate response.

CodePudding user response:

You are not doing anything wrong.

jwt.verify() throws an error for several reasons (not only Expiration). If there is an error jwt.verify does not return anything, it throws an error instead. So in your catch, you can handle that error.

If the error is related to token, it has this format:

err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }

Other errors related to the token are:

'invalid token' - the header or payload could not be parsed
'jwt malformed' - the token does not have three components (delimited by a .)
'jwt signature is required'
'invalid signature'

In your catch session you can handle the different type of error for example like so.

try {
    // your code
} catch (e) {
    const errorObj= {  status: 'fail',
    message: 'An unhandeld error occured'
  }

if (!e?.name) res.status(500).json(errorObj) // if there is no name property send undandelt error message

switch (e.name) {
    case 'JsonWebTokenError' :
        errorObj.message = 'invalid token'
        break;
    case 'TokenExpiredError' :
        errorObj.message = 'token expired'
        break;

        // analyse other errors full list here: https://www.npmjs.com/package//jsonwebtoken#:~:text=Errors & Codes,-Possible thrown errors
    default:
        errorObj.message = 'unhandeld token error'
        break;
}

res.status(500).json(errorObj) 
}

 
  • Related