@hapi/basic Basic Authentication Plugin
repository·master·Indexed 40 days ago
https://github.com/hapijs/basicA basic authentication plugin for the hapi web framework ecosystem, version 7.0.2. It provides the 'basic' authentication scheme and requires Hapi version >=20.0.0. The plugin allows developers to define authentication strategies using a custom validate function to verify usernames and passwords.
What's inside hapi-basic
- @hapi/basic is a basic authentication plugin designed for the hapi web framework ecosystem. While it is optimized to work seamlessly with hapi and its components, it is also capable of working independently or with other web frameworks.
Register the @hapi/basic plugin
masterTo use Basic authentication in a Hapi server, register the
@hapi/basicplugin. This plugin adds thebasicauthentication scheme to your server's authentication registry viaserver.auth.scheme('basic', ...).Note that this plugin requires Hapi version
>=20.0.0.await server.register({ plugin: require('@hapi/basic') });Configure a Basic authentication strategy
masterOnce the plugin is registered, you can define a Basic authentication strategy using
server.auth.strategy(). You must provide avalidatefunction in the options object. This function is responsible for verifying the username and password.Validation Function Signature
The
validatefunction is called by the scheme and must return an object with the following properties:isValid(boolean): Indicates if the credentials are correct.credentials(object, optional): The user credentials to be attached to the request if validation succeeds.response(any, optional): If provided, the server will immediately return this response and bypass further processing.
Strategy Options
Option Type Description validatefunctionRequired. An async function (request, username, password, h) => { isValid, credentials, response }allowEmptyUsernamebooleanIf true, allows the username to be an empty string. Defaults tofalse.unauthorizedAttributesobjectAttributes to include in the unauthorized error response. Error Handling
- If the
Authorizationheader is missing or does not start withbasic, the server throws a401 Unauthorizederror. - If the header format is invalid (e.g., missing the colon in the base64 decoded string), the server throws a
400 Bad Requesterror.
server.auth.strategy('my-strategy', 'basic', { validate: async (request, username, password, h) => { // Your logic to check username and password const isValid = (username === 'user' && password === 'pass'); if (isValid) { return { isValid: true, credentials: { user: username } }; } return { isValid: false }; } }); // Apply to a route server.route({ method: 'GET', path: '/secure', options: { auth: 'my-strategy' }, handler: (request, h) => { return `Hello ${request.auth.credentials.user}`; } });