Skip to content

Repository files navigation

hapi-field-auth

Hapi server plugin for field-level authorization.

main workflowCoverage StatusDependencies StatusMaintainabilitynodecode styleLicense Status

Tested with

  • Node 22, Hapi 20/21

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:

constHapi=require('@hapi/hapi');consthapiAuthBasic=require('@hapi/basic');consthapiFieldAuth=require('hapi-field-auth');constserver=newHapi.Server({port: 3000,});constprovision=async()=>{awaitserver.register([hapiAuthBasic,hapiFieldAuth]);// ...awaitserver.start();};provision();

Your route configuration may look like this:

server.route({method: 'PATCH',path: '/example',options: {auth: {access: {// route-level auth -> HTTP 401/403scope: ['write','write.extended'],// multiple scopes on route-level},},validate: {payload: ExampleSchema,// Joi schema validation -> HTTP 400},plugins: {'hapi-field-auth': [{// add field-level authorization -> HTTP 403fields: ['myProtectedField'],// request payload propertiesscope: ['write.extended'],// restricted scopes on field-level},{fields: ['activeUntil','validUntil'],scope: ['write.extended'],// restricted scopes on field-level...validate: Joi.date().min('now').allow(null),// ...OR additional Joi schema -> HTTP 400}],},},handler: function(request,h){// ...}});

About

Hapi plug-in for field-level authorization

Topics

Resources

Stars

3 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages