hapi-field-auth
Hapi server plugin for field-level authorization.
Tested with
- Node 14/16, Hapi 18/19/20, Joi 17
- Node 10, Hapi 18, Joi 16
Install
npm install hapi-field-auth
Purpose
This plugin provides field-level authorization (not authentication)
for Hapi routes -- particularly useful for PATCH routes.
If the request payload has fields with special constraints
in respect to the scope
of the authenticated user,
this plugin allows restricting access on field-level
and adding field validation depending on the scope
.
A prerequisite is authentication.
Use any authentication plugin, e.g., hapi-auth-basic
or hapi-auth-bearer-token
.
The authentication plugin must properly set request.auth.credentials.scope
with the authenticated user's scope for this plugin to work.
Dynamic scopes referring to the request object (query, params, payload, and credentials)
are supported, e.g., user-{params.id}
. Prefix characters !
and +
are not (yet) supported.
Usage
Register the plugin with Hapi server like this:
const Hapi = require('@hapi/hapi');
const hapiAuthBasic = require('@hapi/basic');
const hapiFieldAuth = require('hapi-field-auth');
const server = new Hapi.Server({
port: 3000,
});
const provision = async () => {
await server.register([hapiAuthBasic, hapiFieldAuth]);
await server.start();
};
provision();
Your route configuration may look like this:
server.route({
method: 'PATCH',
path: '/example',
options: {
auth: {
access: {
scope: ['write', 'write.extended'],
},
},
validate: {
payload: ExampleSchema,
},
plugins: {
'hapi-field-auth': [{
fields: ['myProtectedField'],
scope: ['write.extended'],
}, {
fields: ['activeUntil', 'validUntil'],
scope: ['write.extended'],
validate: Joi.date().min('now').allow(null),
}],
},
},
handler: function (request, h) {
}
});