toymachiner62 / hapi-authorization

ACL plugin for hapijs
MIT License
80 stars 25 forks source link

hapi-authorization

hapi-authorization 4 only supports hapi 17+ for hapi 16 please use hapi-authorization 3

ACL support for hapijs apps

npm version Build Status Coverage Status Dev Dependencies

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.

Support

Usage

Note: To use hapi-authorization you must have an authentication strategy defined.

There are 2 ways to use hapi-authorization:

  1. With the default roles which are: "SUPER_ADMIN", "ADMIN", "USER", "GUEST"
  2. By defining your own roles

Using hapi-authorization with default roles

  1. Include the plugin in your hapijs app. Example:
    
    let plugins = [
    {
        plugin: require('hapi-auth-basic')
    },
    {
        plugin: require('hapi-authorization')
        options: {
          roles: false  // By setting to false, you are not using an authorization hierarchy and you do not need to specify all the potential roles here
        }
    }
    ];

await server.register(plugins);


## Using hapi-authorization with custom roles
1. Include the plugin in your hapijs app.
Example:
```js
let plugins = [
    {
        plugin: require('hapi-auth-basic')
    },
    {
        plugin: require('hapi-authorization'),
        options: {
            roles: ['OWNER', 'MANAGER', 'EMPLOYEE'] // Can also reference a function which returns an array of roles
        }
    }
];

await server.register(plugins);

Whitelist Routes That Require Authorization

If you want no routes require authorization except for the ones you specify in the route config, add hapiAuthorization instructions with the role(s) that should have access to the route configuration.

Example:

Authorize a single role

server.route({ method: 'GET', path: '/', options: {
  plugins: {'hapiAuthorization': {role: 'ADMIN'}},  // Only ADMIN role
  handler: (request, h) => { return "Great!"; }
}});

Authorize multiple roles

server.route({ method: 'GET', path: '/', options: {
  plugins: {'hapiAuthorization': {roles: ['USER', 'ADMIN']}},
  handler: (request, h) => { return "Great!"; }
}});

Blacklist All Routes To Require Authorization

If you want all routes to require authorization except for the ones you specify that should not, add hapiAuthorization instructions with the role(s) that should have access to the server.connection options. Note that these can be overridden on each route individually as well.

Example:

let server = new Hapi.server({
    routes: {
        plugins: {
            hapiAuthorization: { roles: ['ADMIN'] }
        }
    }
});

Override the authorization to require alternate roles

server.route({ method: 'GET', path: '/', options: {
  plugins: {'hapiAuthorization': {role: 'USER'}},   // Only USER role
  handler: (request, h) => { return "Great!" ;}
}});

Override the authorization to not require any authorization

server.route({ method: 'GET', path: '/', options: {
  plugins: {'hapiAuthorization': false},
  handler: (request, h) => { return "Great!"; }
}});

Note: Every route that uses hapiAuthorization must be protected by an authentication schema either via auth.strategy.default('someAuthStrategy') or by specifying the auth on the route itself.

Full Example using hapi-auth-basic and hapi-authorization

const Hapi = require('hapi');
const modules = require('./modules');

// Instantiate the server
let server = new Hapi.Server();

/**
 * The hapijs plugins that we want to use and their configs
 */
let plugins = [
    {
        register: require('hapi-auth-basic')
    },
    {
        register: require('hapi-authorization'),
        options: {
            roles: ['OWNER', 'MANAGER', 'EMPLOYEE']
        }
    }
];

let validate = (username, password) => {
    // Perform authentication and respond with object that contains a role or an array of roles
    return {username: username, role: 'EMPLOYEE'};
}

/**
 * Setup the server with plugins
 */
await server.register(plugins);
server.start().then(() => {

    server.auth.strategy('simple', 'basic', {validateFunc: validate});
    server.auth.default('simple');

    /**
     * Add all the modules within the modules folder
     */
    for(let route in modules) {
        server.route(modules[route]);
    }

    /**
     * Starts the server
     */
    server.start()
        .then(() => {
            console.log('Hapi server started @', server.info.uri);
        })
        .catch((err) => {
            console.log(err);
        });
})
.catch((err) => {
  // If there is an error on server startup
  throw err;
});

Gotchas

Auth before routes

You must define your auth strategy before defining your routes, otherwise the route validation will fail.

Plugin Config

Route config of supported parameters: