Home > Mobile >  express jwt error handling in nest js graphql
express jwt error handling in nest js graphql

Time:11-30

I use express JWT with nest js and use it in gateway graphql. I want to return error when my token has error including expiration error or invalid error after calling any graphql api.

Here is the code that I use express JWT in main file of my gateway:

app.use(
    graphqlUploadExpress(),
    expressJwt({
      secret: secretCallback,
      algorithms: ['HS256'],
      credentialsRequired: false,
    }),
  );

and the following code is my validation when token is invalid:

function (err, req, res, next) {
    const { ip, method, originalUrl, headers } = req;
    const requestMeta = { headers, ip, method, originalUrl, error: err };
    if (err.message === 'jwt expired') {
      Logger.error('Gateway JWT Expired', requestMeta);
      res.send(401, { code: 'gateway-token-expired', message: 'Token is expired' });
    } else if (err.code === 'invalid_token') {
      Logger.error('Gateway JWT Invalid', requestMeta);
      res.send(401, { code: 'gateway-token-invalid', message: 'Token is invalid' });
    } else {
      next(err);
    }
  };

I want that res.status(err.status).send({ message: err.message }); return the error message back to user.

CodePudding user response:

Maybe this could help...

function (err, req, res, next) {
    const { ip, method, originalUrl, headers} = req;
    const requestMeta = { headers, ip, method, originalUrl, error: err};
    if (err.message === 'jwt expired') {
        Logger.error('Gateway JWT Expired', requestMeta);
        res.status(err.status || 401).send({ message: 'Token is expired or gateway-token-expired'});
    } else if (err.code === 'invalid_token') {
        Logger.error('Gateway JWT Invalid', requestMeta);
        res.status(err.status || 401).send({ message: 'Token is invalid or gateway-token-invalid'});
    } else {
        res.status(err.status || 501).send({ message: `${err.message} or ${err.code}`});
    }
}

CodePudding user response:

the problem was that when I send response to client I did not set headers to response to due to this client was getting CROS policy.

 res
    .status(401)
    .set({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' })
    .send({ code: 'gateway-token-expired', message: 'Token is expired' });
  • Related