Basic authentication with Hapi
Basic authentication in Hapi.js, a popular Node.js framework, can be achieved using the 'hapi-auth-basic' plugin. This plugin provides a straightforward way to implement basic authentication for your routes.
Here's a step-by-step guide on how to set up basic authentication with Hapi.js:
bash
npm install @hapi/basic
javascript
领英推荐
const Hapi = require('@hapi/hapi');
const Basic = require('@hapi/basic');
javascript
const server = Hapi.server({
port: 3000,
host: 'localhost',
});
const validate = async (request, username, password, h) => {
// Add your authentication logic here.
// Check if the provided username and password are valid.
// For example, you can compare them against a database.
const isValid = username === 'yourUsername' && password === 'yourPassword';
const credentials = { id: 'user123', name: 'John Doe' }; // Replace with your user data
return { isValid, credentials };
};
const init = async () => {
await server.register(Basic);
server.auth.strategy('simple', 'basic', { validate });
server.auth.default('simple');
// Define your routes here
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello, World!';
},
});
await server.start();
console.log(`Server is running at ${server.info.uri}`);
};
init();
javascript
server.route({
method: 'GET',
path: '/protected',
config: {
auth: 'simple',
},
handler: (request, h) => {
return 'This route is protected!';
},
});
In this example, the '/protected' route is protected with basic authentication, and users will need to provide valid credentials to access it.
Remember to replace the sample username and password in the 'validate' function with your actual authentication logic, such as checking against a database or other user management system.