3

i want to know how to change de response of express-jwt when is unauthorized, i tried with handlers but doesnt work

i need help

// Authorization
const auth = require('express-jwt');

router.get('/', auth({secret: config.secretKey}),async(req,res,next)=>{
  console.log('hola')
})

when the token is invalid return this

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>UnauthorizedError: invalid token
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/lib/index.js:102:22
            <br> &nbsp; &nbsp;at Object.module.exports [as verify] (/Users/luisandrade/code/slothy_/back/node_modules/jsonwebtoken/verify.js:75:12)
            <br> &nbsp; &nbsp;at verifyToken (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/lib/index.js:100:13)
            <br> &nbsp; &nbsp;at fn (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:746:34)
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:1213:16
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:166:37
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:706:43
            <br> &nbsp; &nbsp;at /Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:167:37
            <br> &nbsp; &nbsp;at Immediate._onImmediate (/Users/luisandrade/code/slothy_/back/node_modules/express-jwt/node_modules/async/lib/async.js:1206:34)
            <br> &nbsp; &nbsp;at runCallback (timers.js:810:20)
            <br> &nbsp; &nbsp;at tryOnImmediate (timers.js:768:5)
            <br> &nbsp; &nbsp;at processImmediate [as _immediateCallback] (timers.js:745:5)
        </pre>
    </body>
</html>

but i want this

{
  error: 'some message'
}
Drakezair
  • 31
  • 3

2 Answers2

3

put this just above where you create the server.

app.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        res.status(401).send('invalid token...');
    }
});

You can also handle other errors in this by using next(e), where e is the error from a try catch.

h11
  • 108
  • 1
  • 13
0

Instead of using the default auth middleware imported from express-jwt, you can create your own higher-order middleware that will contain the express-jwt middleware, and add custom logic to it.

In your case, we wish to customize the error handling, and prevent express-jwt from calling next() immediately upon an authorization error. This can be done by calling the express-jwt default middleware while passing a "fake" nextFunction argument.

This can be our "fake" nextFunction, for example:

    // Pass expressjwt a next function that throws a custom error if authentication fails
    const nextWithError = (err: any) => {
      if (err) {
        next(new CustomAuthenticationError(err.message))
      }
    }

And this is how it would look like, written inside our higher-order wrapping middleware:

export function authenticate(req: Request, res: Response, next: NextFunction) {
    // Pass expressjwt a next function that throws an error if authentication fails
    const nextWithError = (err: any) => {
      if (err) {
        next(new AuthenticationError(err.message))
      }
    }
    // Authenticate as usual
    return expressjwt({
      // ...jwt-express options
    })(req, res, nextWithError)
  
}

After that, all you need to do is use the custom wrapping middleware just as you would use the normal express-jwt middleware in your server:

 appRouter.use(authenticate)
 // all the other routes...

This Github issue discusses the same problem, for further reading.