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

wrong error code for UnauthorizedError: invalid signature?

Open VikramTiwari opened this issue 8 years ago • 2 comments

In case of UnauthorizedError: invalid signature? why is 500 being thrown? Shouldn't this be handled gracefully by using 401 status code?

VikramTiwari avatar Nov 20 '16 07:11 VikramTiwari

I'm not sure if this is still an issue for you @VikramTiwari , but I came across your issue while searching for my own invalid signature problem. My guess is that you're not handling the error correctly. express-jwt doesn't handle sending the statuses to the client, you've got to do that in your Express (or whatever) code by handling the error. Here's what I use:

app.use('/api',
  jwt({secret: process.env.AUTH0_CLIENT_SECRET}),
  function(req, res, next){
    // Do stuff here if we have a logged in user, such as:
    // if (!req.user.admin) return res.sendStatus(401);
    // res.sendStatus(200);
    next();
  },
  function(err, req, res, next) {
    if (err.name === 'UnauthorizedError') { 
      return(res.status(401).send('Invalid authorization token'));
    }
  }
);

shankie-codes avatar Jun 14 '17 09:06 shankie-codes

I'm just trying to use this lib for the very first time I get the same error as the OP.

app.use(
    '/graphql',
    expressjwt({
      secret: '3DgjLM20faZv9YwBxHsQ',
      issuer: 'api',
      credentialsRequired: false,
      algorithms: ['HS256'],
    }),
    cors<cors.CorsRequest>(),
    express.json(),
    expressMiddleware(server as ApolloServer<MyContext>, {
      context: async ({ req }: { req: express.Request }) => ({
        req,
        currentUser: undefined,
        prisma,
      }),
    }),
  );

jbeckton avatar Mar 31 '24 21:03 jbeckton