@digipolis/authz
Authorization module which can be used to check the permissions of an authenticated user.
Last updated 3 months ago by vademo .
MIT · Original npm · Tarball · package.json
$ cnpm install @digipolis/authz 
SYNC missed versions from official npm registry.

Build Status Coverage Status

@digipolis/Authz

Authorization module which can be used to check the permissions of an authenticated user.

Table of contents:

Installing

npm:

$ npm i @digipolis/authz

Yarn:

$ yarn add @digipolis/authz

Configuration

Available sources:

authzv2:

For applications which use the User Management Engine and have a JWT token of the authenticated user (mostly API's).

meauthzv2:

For applications which use the User Management Engine and have an OAuth2 access token of the authenticated user (mostly BFF's).

Configuration for the use with the User Management Engine (UM):

Params:
Param Description Values
debug (optional) Set debugging mode true / false (default)
disabled (optional) Disable the authz check. This will allow everything for each token. Only for testing / dev purposes. true / false (default)
source The source to use by default. You can also specify a source in the function call authzv2 / meauthz
sources Object with possible authz sources and their configurations { authzv2: { _config_ }}
tokenLocation (optional) Location of the token on the request object. Used by middleware. Defaults to 'headers.authorization' headers.authorization / session.token (example)
cache (optional) Enable cache. The permissions will be cached based for a token+source with a TTL of 600 (10min) true (default) / false
authzv2: applicationId Name of application from UM _APPLICATION_ID_
authzv2: url Url of the authz api (v2) You can find this on the api-store _URL_OAUTHZ_
authzv2: apiKey Api key. You will need to create an application with a contract with the authz api _APIKEY_
Example:
const { config } = require('@digipolis/authz');

config({
  debug: true,
  source: 'authzv2',
  tokenLocation: 'headers.authorization',
  sources: {
    authzv2: {
      url:  '_URL_AUTHZ_',
      apiKey: '_APIKEY_',
      applicationId: '_APPLICATION_ID_',
    },
    meauthz: {
      url:  '_URL_AUTHZ_',
      apiKey: '_APIKEY_',
      applicationId: '_APPLICATION_ID_',
    },
  },
});

Usage

The module can be used as an express middleware or as a function. The parameter is a string to check a single permission or an array to check multiple permissions. If a permission is missing an Error of the type PermissionError will be thrown.

An example of this can be found in the documentation below and in the example folder.

Usage as express middleware:

Configuration should be done before usage.

const { Router } = require('express');
const { hasPermission } = require('@digipolis/authz');

const router = new Router();

// Check single permission in default source
router.get('/', hasPermission('login-app'), controller);
// Check mutiple permissions in default source
router.get('/', hasPermission(['login-app', 'admin-app']), controller);
// Check permission in default meauthz source
router.get('/', hasPermission('login-app', 'meauthz'), controller);

Usage as function:

Configuration should be done before usage.

const { checkPermission } = require('@digipolis/authz');
const { create } = require('./itemcreator.service');

async function createSomething(params, usertoken) {
    await checkPermission(usertoken, 'login-app'); //throws error if invalid
    await checkPermission(usertoken, ['login-app', 'use-app']); //throws error if invalid
    await checkPermission(usertoken, 'login-app', 'meauthz'); //throws error if invalid
    return create(params);
}

External authorization source:

You can plug in your own implementation for retrieving permissions:

Requirements:
  • Your function should take 1 argument: token. The token will be stripped from the Bearer prefixes.
  • Permissions should be returned as an array.
const { checkPermission, config } = require('@digipolis/authz');
const controller = require('./controller');

function AuthzImplementation (token) {
    // Retrieve the users permissions here
    return ['permission1', 'permission2'];
}

config({
  debug: true,
  source: 'externalAuthz',
  tokenLocation: 'headers.authorization',
  sources: {
    externalAuthz: AuthzImplementation,
    meauthz: {
      url:  '_URL_AUTHZ_',
      apiKey: '_APIKEY_',
      applicationId: '_APPLICATION_ID_',
    },
  },
});

router.get('/', hasPermission('permission1'), controller); // Use own implementation (set as default)
router.get('/', hasPermission('login-app', 'meauthz'), controller); // Use defined meauthz implementation

Permissions list:

Retrieve permissions as a list

  // Default source (set in config)
  const permissions = await getPermissions(req.headers.authorization);

  // specific  source
  const permissionsMeauthz = await getPermissions(req.headers.authorization, 'meauthz');

Returns: Array['string']:

[
    "PERMISSION_1",
    "PERMISSION_2",
    "PERMISSION_3",
]

PermissionError:

Model
{
  ...extends_default_javascript_error
  name: 'PermissionError',
  message: 'Failed to retrieve permissions.' // example
  detail: {
    message: 'Invalid Token' // example
  }
}
Error messages:
  • ApplicationId not configured.
  • Authzv2 not configured.
  • meAuthz not configured.
  • Missing permissions: permission1 Detail
  • Failed to retrieve permissions. Detail
  • No authorization found in header.
  • No source defined for permissions
  • No valid datasource defined for permissions
  • Permission service returned permissions in an unexpected format
Error detail:
Failed to retrieve permissions (example):
{
  message: "Failed to retrieve permissions",
  detail: {"messsage": _error_message_authzv2_api_ }
}
Missing permissions (example):
{
  message: "Missing permissions: permission1",
  detail: {
    missingPermissions: ["permission1"],
    requiredPermissions: "permission1",
    foundPermissions: ["permission2"]
  }
}
Error handling:
Handle error from middleware:
function errorhandler(err, req, res, next) {
  if (err.name === 'PermissionError') {
    return res.status(401).json({
      message: err.message,
      detail: err.detail,
    });
  }
  return next(err);
}

module.exports = errorhandler;
Catch error from function:
try {
  await checkPermission(_TOKEN_, 'login-app');
  return do_something();
} catch (err) {
  if (err.name === 'PermissionError') {
    console.log('Detected authorization error');
  }
  // Handle error in express middleware
  return next(err);
}

Running the tests

Run the tests in this repo:

$ npm run test
$ npm run coverage

Dependencies

Versioning

We use SemVer

for versioning. For the released version check changelog / tags

Authors

  • Olivier Van den Mooter - Initial work - Vademo

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Current Tags

  • 1.1.0                                ...           latest (3 months ago)

2 Versions

  • 1.1.0                                ...           3 months ago
  • 1.0.1                                ...           6 months ago
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 2
Dependencies (4)
Dev Dependencies (9)
Dependents (0)
None

Copyright 2014 - 2016 © taobao.org |