connect-ensure-authorization
This middleware ensures that a user is authorized. If the user is unauthorized, the request returns a JSON error by default or redirects the user with additional configuration.
Table of contents
Install
Yarn
$ yarn add connect-ensure-authorization
NPM
$ npm install connect-ensure-authorization
Usage
Ensure scope
In this example, an application has a todos API endpoint. A user must be authorized before accessing this endpoint.
const express = ;const ensureScope = ; const app = ; // req.user should be like:// {// username: 'bob', <-- dummy data// fullName: 'Bob', <-- dummy data// scopes: ['todos:read'] <-- used for scope checking// } app;
If a user is not authorized when attempting to access this API, the request will return the default 403 status code with the default message "Forbidden".
Ensure functions
The following ensure functions are available:
Function | User property |
---|---|
ensureScope |
scopes |
ensurePermission |
permissions |
ensureRole |
roles |
ensureGroup |
groups |
All functions will check its corresponding user property. The user property should contain an array with strings. The ensure function does an Array.includes
check. This default implementation can be modified to your custom requirement.
Custom ensure implementation
The ensure implementation can be overwritten with a custom implementation. This function must return a Promise
or a Boolean
.
const express = ;const initialize: initializeAuthorization ensureScope } = ; const app = ; const onEnsureScope = { if userscopes ; else ; }; ; app;
The other ensure implementations are also supported to be overwritten (by passing onEnsurePermission
, onEnsureRole
and onEnsureGroup
).
Custom status code and/or message
The middleware can be configured to return another status code and/or message when unauthorized.
const express = ;const initialize: initializeAuthorization = ; const app = ; ; app;
Redirect instead of return JSON
The following example redirects to /forbidden
instead of returning a JSON message.
const express = ;const initialize: initializeAuthorization = ; const app = ; app;
Custom user property
If you are using Passport, this defaultly sets the req.user
after logging in. This can be modified to for example req.account
.
const express = ;const initialize: initializeAuthorization = ; const app = ; // req.account should be like:// {// accountName: 'bob', // dummy data// fullName: 'Bob', // dummy data// scopes: ['todos:read'] <-- used for scope checking// } app;
Usage with Passport
Take a look at the integration test for some inspiration.
I have also created a single file example repository using this module: https://github.com/allardvanderouw/express-api-passport-local-mongo-session-example/blob/master/server.js