@whook/authorization
TypeScript icon, indicating that this package has built-in type declarations

16.1.0 • Public • Published

@whook/authorization

A wrapper to provide authorization support to a Whook server

GitHub license

This Whook wrapper ties authentication with only two kinds of input:

  • the authorization header which allows several mechanisms to be used including custom ones (this module is using http-auth-utils under the hood). This is the recommended way to authenticate with a server.
  • the access_token defined by the RFC6750 that allows providing the token via query parameters for convenience (mostly for development purpose). Note that you can disable it by setting the DEFAULT_MECHANISM constant to an empty string.

Note that the form-encoded body parameter defined by the bearer authentication RFC is volontarily not supported since nowadays everyone uses JSON and there is no situations where one could not set the token in headers.

To use this wrapper, you'll have to create an authentication service. Here is a simple unique token based implementation (usually in src/services/authentication.ts):

import { autoService } from 'knifecycle';
import { YError } from 'yerror';
import {
  AuthenticationService,
  BaseAuthenticationData,
} from '@whook/authorization';

export type AuthenticationConfig = {
  TOKEN: string;
};

export type BearerPayload = { hash: string };
export type MyAuthenticationService = AuthenticationService<
  BearerPayload,
  BaseAuthenticationData & {
    userId: number;
  }
>;

export default autoService(initAuthentication);

async function initAuthentication({
  TOKEN,
}: AuthenticationConfig): Promise<MyAuthenticationService> {
  const authentication: MyAuthenticationService = {
    // The authentication service must have a check
    // method which take the type of authentication
    // used by the client and its parsed payload
    check: async (type, data) => {
      if (type === 'bearer') {
        if (data.hash === TOKEN) {
          // When successful, the authentication check
          // must return an object with at least a `scopes`
          // property containing an array of the actual
          // scopes the authentication check resolved to
          return {
            applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
            userId: 1,
            scope: 'admin',
          };
        }
        throw new YError('E_BAD_BEARER_TOKEN', type, data.hash);
      }
      // Of course, the service must check the auth type
      // and fail if not supported to avoid security issues
      throw new YError('E_UNEXPECTED_AUTH_TYPE', type);
    },
  };

  return authentication;
}

The properties added next to the scopes one will be passed to the wrapped handlers and an authenticated property will also be added in order for handlers to know if the client were authenticated.

Then, simply install this plugin:

npm i @whook/authorization;

Declare this module types in your src/whook.d.ts type definitions:

+ import type { WhookAuthorizationConfig } from '@whook/authorization';

// ...

declare module 'application-services' {

  // ...

  export interface AppConfig
    extends WhookBaseConfigs,
      WhookAuthorizationConfig,
      WhookSwaggerUIConfig,
      WhookCORSConfig,
      APIConfig,
  export interface AppConfig
    extends WhookBaseConfigs,
+    WhookAuthorizationConfig,
    JWTServiceConfig {}

  // ...

}

Then add the config and the errors descriptors or provide your own (usually in src/config/common/config.js):

// ...
import { DEFAULT_ERRORS_DESCRIPTORS } from '@whook/http-router';
+ import {
+   AUTHORIZATION_ERRORS_DESCRIPTORS,
+ } from '@whook/authorization';
import type { AppConfig } from 'application-services';

// ...

const CONFIG: AppConfig = {
  // ...
-   ERRORS_DESCRIPTORS: DEFAULT_ERRORS_DESCRIPTORS,
+   ERRORS_DESCRIPTORS: {
+     ...DEFAULT_ERRORS_DESCRIPTORS,
+     ...AUTHORIZATION_ERRORS_DESCRIPTORS,
+   },
+   DEFAULT_MECHANISM: 'bearer',
  // ...
};

export default CONFIG;

And finally declare this plugin in the src/index.ts file of your project:

  // ...

  $.register(
    constant('HANDLERS_WRAPPERS', [
      'wrapHandlerWithCORS',
+      'wrapHandlerWithAuthorization',
    ]),
  );

  // ...

  $.register(
    constant('WHOOK_PLUGINS', [
      ...WHOOK_DEFAULT_PLUGINS,
      '@whook/cors',
+      '@whook/authorization',
    ]),
  );

  // ...

To see a complete usage of this wrapper, you may have a look at the @whook/example project.

API

initWrapHandlerWithAuthorization(services) ⇒ Promise.<Object>

Wrap an handler to check client's authorizations.

Kind: global function
Returns: Promise.<Object> - A promise of an object containing the reshaped env vars.

Param Type Description
services Object The services ENV depends on
[services.MECHANISMS] Array The list of supported auth mechanisms
[services.DEFAULT_MECHANISM] string The default authentication mechanism
services.authentication Object The authentication service
services.log Object A logging service

Authors

License

MIT

Package Sidebar

Install

npm i @whook/authorization

Weekly Downloads

118

Version

16.1.0

License

MIT

Unpacked Size

104 kB

Total Files

15

Last publish

Collaborators

  • nfroidure