### Hapi Basic Authentication Setup Source: https://github.com/hapijs/basic/blob/master/API.md Demonstrates how to configure and use the @hapi/basic plugin for basic HTTP authentication in a hapi server. Includes user validation logic using Bcrypt for password comparison. ```javascript const Bcrypt = require('bcrypt'); const Hapi = require('@hapi/hapi'); const users = { john: { username: 'john', password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm', // 'secret' name: 'John Doe', id: '2133d32a' } }; const validate = async (request, username, password, h) => { if (username === 'help') { return { response: h.redirect('https://hapijs.com/help') }; // custom response } const user = users[username]; if (!user) { return { credentials: null, isValid: false }; } const isValid = await Bcrypt.compare(password, user.password); const credentials = { id: user.id, name: user.name }; return { isValid, credentials }; }; const main = async () => { const server = Hapi.server({ port: 4000 }); await server.register(require('@hapi/basic')); server.auth.strategy('simple', 'basic', { validate }); server.auth.default('simple'); server.route({ method: 'GET', path: '/', handler: function (request, h) { return 'welcome'; } }); await server.start(); return server; }; main() .then((server) => console.log(`Server listening on ${server.info.uri}`)) .catch((err) => { console.error(err); process.exit(1); }); ``` -------------------------------- ### Hapi Basic Authentication Scheme Options Source: https://github.com/hapijs/basic/blob/master/API.md Details the configuration options for the 'basic' authentication scheme in hapi, including the required `validate` function and optional parameters. ```APIDOC 'basic' Authentication Scheme Options: Options: - validate: (required) a user lookup and password validation function. Signature: [async] function(request, username, password, h) Parameters: - request: The hapi request object. - username: The username received from the client. - password: The password received from the client. - h: The response toolkit. Returns: An object { isValid, credentials, response } - isValid: boolean - true if authentication is successful, false otherwise. - credentials: object - Passed back to the application in request.auth.credentials. - response: object (optional) - A takeover response (e.g., redirect). Note: Throwing an error from this function replaces the default Boom.unauthorized error. - allowEmptyUsername: (optional) boolean - if true, allows requests with an empty username. Defaults to false. - unauthorizedAttributes: (optional) object - Passed directly to Boom.unauthorized if no custom error is thrown. Useful for setting realm attribute in WWW-Authenticate header. Defaults to undefined. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.