0.0.6 • Published 3 months ago

@flexiloans/auth-nest v0.0.6

Weekly downloads
-
License
UNLICENSED
Repository
-
Last release
3 months ago

Auth & Authz middleware

auth-nest is an npm package designed to specifically authenticate and authorize APIs in Nest.js applications. It provides two middleware functions: authenticate and authorize that can be easily integrated into your application to secure routes and resources.

We use JWT validations to authenticate routes.

Installation

Create a file .npmrc in the root and add the following in it

//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Open a terminal and set the var NPM_TOKEN

export NPM_TOKEN="ADD_YOUR_TOKEN_HERE"

Install the package using npm:

npm i @flexiloans/auth-nest

Token Headers

  • M2M token We expect the machine token to be set in headers on the key internal-access-token

  • User token We expect the user token to be set in headers on the key access-token

Usage

Importing and initialising the package

import { init } from '@flexiloans/auth-nest';

<!-- Base URL is where the authentication server is hosted -->
<!-- SERVICE_NAME is the name of service installing this package  -->
const AUTH_URL = "http://AUTH_URL";
const SERVICE_NAME = "FLKYC";

import { init } from '@flexiloans/auth-nest';

export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        

        const AUTH_URL = 'https://shield-dev.flexiloans.com';
        const SERVICE_NAME = 'FLKYC';
        init(AUTH_URL, SERVICE_NAME);
    }
}

Authenticaiton and Authorization will not work if the library is not initialised.

Middleware Functions

Use the authenticate middleware to ensure that a user is authenticated before accessing a route.

import { AuthenticationMiddleware } from '@flexiloans/auth-nest';

export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        

        const AUTH_URL = 'https://shield-dev.flexiloans.com';
        const SERVICE_NAME = 'FLKYC';
        init(AUTH_URL, SERVICE_NAME);
        consumer.apply(AuthenticationMiddleware).forRoutes('*');
    }
}

Use the authorize middleware is used to check if a user has the necessary permissions to access a resource

import { AuthorizationMiddleware } from '@flexiloans/auth-nest';

export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        consumer.apply(RequestMiddleware).forRoutes('*');

        const AUTH_URL = 'https://shield-dev.flexiloans.com';
        const SERVICE_NAME = 'FLKYC';
        init(AUTH_URL, SERVICE_NAME);
        consumer.apply(AuthenticationMiddleware).forRoutes('*');
        consumer.apply(AuthorizationMiddleware).forRoutes('*');
    }
}

Error Handling

If any error occurs during authentication or authorization, the middleware will throw an appropriate Unauthenticated, Unauthorized or Internal Server error that you need to handle