A wrapper to provide authorization support to a Whook server
npm install @whook/authorization[//]: # ( )
[//]: # (This file is automatically generated by a metapak)
[//]: # (module. Do not change it except between the)
[//]: # (content:start/end flags, your changes would)
[//]: # (be overridden.)
[//]: # ( )

[//]: # (::contents:start)
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 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 insrc/services/authentication.ts):
``ts
import { autoService } from 'knifecycle';
import { YError } from 'yerror';
import {
type AuthenticationService,
type 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
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 wrappedauthenticated
handlers and an property will also be added in order for
handlers to know if the client were authenticated.
Then, simply install this plugin:
`sh`
npm i @whook/authorization;
Declare this module types in your src/whook.d.ts type definitions:
`diff
+ import {
+ type WhookAuthorizationConfig,
+ type WhookAuthenticationExtraParameters
+ type WhookBaseAuthenticationData
+ } from '@whook/authorization';
// ...
declare module 'application-services' {
// ...
export interface AppConfig
extends WhookBaseConfigs,
WhookAuthorizationConfig,
WhookSwaggerUIConfig,
WhookCORSConfig,
APIConfig,
export interface AppConfig
extends WhookBaseConfigs,
+ WhookAuthorizationConfig,
JWTServiceConfig {}
// ...
}
// ...
declare module '@whook/whook' {
// ...
+ export interface WhookRouteHandlerExtraParameters
+ extends WhookAuthenticationExtraParameters {}
// ...
}
+declare module '@whook/authorization' {
+ export interface WhookAuthenticationData extends WhookBaseAuthenticationData {
+ userId: string;
+ }
+}
`
Then add the config and the errors descriptors or provide your own (usually in
src/config/common/config.js):
`diff
// ...
import { DEFAULT_ERRORS_DESCRIPTORS } from '@whook/whook';
+ 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:
`diff
// ...
$.register(
constant('ROUTES_WRAPPERS_NAMES', [
'wrapRouteHandlerWithCORS',
+ 'wrapRouteHandlerWithAuthorization',
]),
);
// ...
$.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.
[//]: # (::contents:end)
Promise.<Object>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 |