Custom error messages in JWT Auth [Adonis 4.0]

For security purposes and best practices, I would like to show the message “Invalid username or password” instead of showing only if the user does not exists or the password does not match. How can I override the UserNotFoundException or PasswordMisMatchException used in the validate function inside Jwt Scheme ?

Never mind, I just found that I can override that exceptions in the hooks.js that are located inside the start folder. Here is an example if any one needs something like this:

const {hooks} = require('@adonisjs/ignitor')

hooks.after.providersBooted(() => {
  const Exception = use('Exception')

  Exception.handle('UserNotFoundException', async (error, {response, session}) => {
    response.status(error.status).send({
      status: error.status,
      message: 'Invalid username or password',
      code: 102
    })
  })

  Exception.handle('PasswordMisMatchException', async (error, {response, session}) => {
    response.status(error.status).send({
      status: error.status,
      message: 'Invalid username or password',
      code: 102
    })
  })
})

Generally people think that when a login fails, it’s an attack on their system and confuses the flow to fool the attacker

Whereas in most cases it’s a genuine user trying to login and now he/she doesn’t know whether the username is wrong or the password

Even though we have the flexibility to tell them the right information we just choose not to

3 Likes