Additional authentication toolbox for HapiJS.
It includes:
Hapi = 9.*
This plugin provides an easy way to implement token based authentication, it could be a good solution for internal APIs, for external APIs please consider using oAuth instead. All you have to do is to provide a method that validates a token and returns the related user in case the token is valid. In order to use this feature, you need to register the plugin and enable 'auth-token' authentication schema that the plugin provides.
Example:
// Sample token validator, you may replace with your own implementation.
function validateToken(token, cb) {
return cb(null, {_id: '123', name: 'Test User'}); // Returns a sample user, this is the authenticated user.
}
var server = Hapi.createServer(0);
// Register the plugin
server.register('hapi-auth-extra', {
tokenAuth: {
tokenValidator: validateToken // Set the custom validator
}
}, function(err) {
server.route({ method: 'GET', path: '/', config: {
auth: 'default', // Protect this route
handler: function (request, reply) { reply("Authorized");}
}});
// Load the authentication schema
server.auth.strategy('default', 'auth-token');
});
You can use this plugin to add ACL and protect your routes. you can configure required roles and allow access to certain endpoints only to specific users.
In order to activate the plugin for a specific route, all you have to do is to add hapiAuthExtra instructions to the route configuration, for example:
server.route({ method: 'GET', path: '/', config: {
auth: 'default',
plugins: {'hapiAuthExtra': {role: 'ADMIN'}},
handler: function (request, reply) { reply("Great!");}
}});
Note: every route that uses hapiAuthExtra must be protected by an authentication schema (auth: true).
server.route({ method: 'POST', path: '/product', config: {
auth: 'default', // Protected route
plugins: {'hapiAuthExtra': {role: 'ADMIN'}}, // Only admin
handler: function (request, reply) { reply({title: 'New product'}).code(201);}
}});
server.route({ method: 'DELETE', path: '/video/{id}', config: {
auth: 'default', // Protected route
plugins: {'hapiAuthExtra': {
validateEntityAcl: true, // Validate the entity ACL
aclQuery: function(id, cb) { // This query is used to fetch the entitiy, by default auth-extra will verify the field _user.
cb(null, {_user: '1', name: 'Hello'}); // You can use and method you want as long as you keep this signature.
}
}},
handler: function (request, reply) { reply("Authorized");}
}});