Search code examples
basic-authenticationhapi.js

Hapi basic auth validate is not called


The validate function for basic

await server.register(require('@hapi/basic'));
const validate = async (request, email, password, id_customer) => {
    console.log(request)
        if (!email || !password || !id_customer) {
            return { credentials: null, isValid: false };
        }
    
        const results = await getHash(id_customer);
    
        if (results.length == 0) {
            return { credentials: null, isValid: false };
        }
    
        if (bcrypt.compareSync(password, results[0]['passwd'])) {
            const credentials = { id: id_customer, email: email };
    
            return { isValid: true, credentials };
        }
        return { credentials: null, isValid: false };
    };
server.auth.strategy('simple', 'basic', { validate });

Route example :

{
    method: 'POST',
    path: '/home/getCategories',
    config: {
        auth: 'simple',
        description: 'Get Home',
        payload: {
            multipart: true
        },
        handler: Home.getCategories
    },
   /* options: {
        auth: 'simple'
    },*/
    //handler: Home.getCategories
},

Here is the axios call from the App :

axios.post('https://api.domain.com/home/getCategories', {
    code: code
  },
  {
    headers: {
        'email': email,
        'password': password,
        'id_customer': id_customer
    },
  })

When I do the call I got a 401 unauthorized but I cant see the output of 'console.log(request)'

Any help ?


Solution

  • Have you tried the following? What version of Hapi.js are you using?

    const categoryPostValidation = {
      payload: Joi.object({
        name: Joi.string().label("Name").min(1).max(30).error((errors) => new Error('Name is invalid, and must be 1 to 30 characters in length')).required(),
        description: Joi.string().label("Description").min(1).max(255).error((errors) => new Error('Description is invalid, and must be 1 to 255 characters in length')).required()
      }),
      failAction: async (request, h, err) => {
        throw err;
      }
    };
    
    const categoryPostRouteOptions = {
      description: "Posts one category.",
      cors: true,
      payload: {
        output: 'data', // These are default options
        parse: true // These are default options
      },
      auth: {
          mode: 'required' // or 'try', etc
          strategy: 'simple'
      },
      validate: categoryPostValidation,
      handler: Home.getCategories
    };
    
    
    {
        method: 'POST',
        path: '/home/getCategories',
        options: categoryPostRouteOptions
    },