0.13.1 • Published 3 months ago

@loopx/authentication-service v0.13.1

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

@loopx/authentication-service

Overview

A Loopback Microservice for handling authentications. It provides -

To get started with a basic implementation of this service, see /sandbox/auth-basic-example.

For a more elaborate and custom implementation that overrides the default models and repositories, see /sandbox/auth-multitenant-example.

Working and Flow

This module uses the decorators provided by loopback4-authentication and loopback4-authorization. For reference, below is the flow for the login code generation that uses the authenticate client, authenticate user and authorization decorators from these npm packages -

Login Flow

Installation

npm i @loopx/authentication-service

Usage

  • Create a new Loopback4 Application (If you don't have one already) lb4 testapp
  • Install the authentication service npm i @loopx/authentication-service
  • Set the environment variables.
  • Run the migrations.
  • Add the AuthenticationServiceComponent to your Loopback4 Application (in application.ts).

    // import the AuthenticationServiceComponent
    import {AuthenticationServiceComponent} from '@loopx/authentication-service';
    
    // add Component for AuthenticationService
    this.component(AuthenticationServiceComponent);
  • Set up a Loopback4 Datasource with dataSourceName property set to AuthDbSourceName. You can see an example datasource here.

  • Set up a Loopback4 Datasource for caching tokens with dataSourceName property set to AuthCacheSourceName.
  • Bind any of the custom providers you need.
  • OTP -

    • Implement OtpSenderProvider(refer this) in your application and bind it to its respective key in application.ts
    import {AuthServiceBindings, VerifyBindings} from '@loopx/authentication-service';
    
    this.bind(VerifyBindings.OTP_SENDER_PROVIDER).toProvider(OtpSenderProvider);
    this.bind(AuthServiceBindings.MfaConfig).to({
      secondFactor: STRATEGY.OTP,
    });
    this.bind(AuthServiceBindings.OtpConfig).to({
      method: OtpMethodType.OTP,
    });
    • This provider is responsible for sending OTP to user.
    • By default OTP is valid for 5 minutes. To change it, set OTP_STEP and OTP_WINDOW ( refer otp-options) as per your need in .env.
  • Google Authenticator -

    • To use google Authenticator in your application, add following to application.ts
    import {AuthServiceBindings} from '@loopx/authentication-service';
    
    this.bind(AuthServiceBindings.MfaConfig).to({
      secondFactor: STRATEGY.OTP,
    });
    this.bind(AuthServiceBindings.OtpConfig).to({
      method: OtpMethodType.GOOGLE_AUTHENTICATOR,
    });
  • Set APP_NAME in .env.

  • To authenticate using only OTP or Authenticator app, use the following APIs:

    • /send-otp
    • /auth/check-qr-code
    • /auth/create-qr-code
    • /verify-otp
  • Two-Factor-Authentication -

    • As of now, 2nd Factor will always be either OTP or Google Authenticator.
    • Implement MfaProvider(refer this) in your application and bind it to its respective key in application.ts
    import {VerifyBindings} from '@loopx/authentication-service';
    
    this.bind(VerifyBindings.MFA_PROVIDER).toProvider(MfaProvider);
    • It works for almost all authentication methods provided by this service.
    • Use /verify-otp to enter otp or code from authenticator app.
  • Start the application npm start

Environment Variables

Setting up a DataSource

Here is a sample Implementation DataSource implementation using environment variables and PostgreSQL as the data source. The auth-multitenant-example utilizes both Redis and PostgreSQL as data sources.

import {LifeCycleObserver, inject, lifeCycleObserver} from '@loopback/core';
import {juggler} from '@loopback/repository';

import {AuthDbSourceName} from '@loopx/authentication-service';

const config = {
  name: AuthDbSourceName,
  connector: 'postgresql',
  url: '',
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_DATABASE,
  schema: process.env.DB_SCHEMA,
};

@lifeCycleObserver('datasource')
export class AuthenticationDbDataSource extends juggler.DataSource implements LifeCycleObserver {
  static dataSourceName = AuthDbSourceName;
  static readonly defaultConfig = config;

  constructor(
    // You need to set datasource configuration name as 'datasources.config.Authentication' otherwise you might get Errors
    @inject('datasources.config.authentication', {optional: true})
    dsConfig: object = config,
  ) {
    super(dsConfig);
  }
}

Database Schema

Auth DB Schema

Providers

You can find documentation for some of the providers available in this service here

Using AZURE AD for OAuth

Passport strategy for authenticating via Azure Ad using passport-azure-ad. Make sure you have an account on Azure and have your application registered. Follow the steps here.

Application Binding

To use this in your application bind AuthenticationServiceComponent the component in your appliation.

import {AuthenticationServiceComponent} from '@loopx/authentication-service';

this.component(AuthenticationServiceComponent);

Set the environment variables

Refer the .env.example file to add all the relevant env variables for Azure Auth. Note - For boolean values that need to passed as false keep them blank.

We are using cookie based approach instead of session based, so the library requires a cookie-parser middleware. To bind the middleware to you application set AZURE_AUTH_ENABLED=true in env file so the middleware will be added to the sequence.

Also the verifier function uses Signup provider whose implementation needs to be added by the user.

Bind the provider key to its corresponding value.

this.providers[SignUpBindings.AZURE_AD_SIGN_UP_PROVIDER.key] = AzureAdSignupProvider;
export class AzureAdSignupProvider implements Provider<AzureAdSignUpFn> {
  value(): AzureAdSignUpFn {
    // sonarignore:start
    return async profile => {
      // sonarignore:end
      throw new HttpErrors.NotImplemented(`AzureAdSignupProvider not implemented`);
    };
  }
}

Also bind VerifyBindings.AZURE_AD_PRE_VERIFY_PROVIDER and VerifyBindings.AZURE_AD_POST_VERIFY_PROVIDER to override the basic implementation provided by default.

Authorizing Public & Private Clients

In order to authorize public and private clients separately in your application, add the following to application.ts before binding AuthenticationComponent

import {AuthenticationBindings, AuthenticationConfig} from 'loopback4-authentication';

this.bind(AuthenticationBindings.CONFIG).to({
  secureClient: true,
} as Authentication
Config
)
;

Authorizing Public & Private Clients-Migrations

add client_type column to auth_clients table with values public/private

ALTER TABLE main.auth_clients
ADD client_type varchar(100) DEFAULT 'public';

Authenticating JWT using RSA Encryption

In order to authenticate JWT token using RSA encrytion, we need to provide JWT_PUBLIC_KEY and JWT_PRIVATE_KEY where the JWT_PUBLIC_KEY and JWT_PRIVATE_KEY are the paths to your public and private keys(.pem files).Steps to create Public key and private key are as follows:

-For creating RSA key pair,use the following command: To generate private key of length 2048:

openssl genrsa -out private.pem 2048

To generate public key:

openssl rsa -in private.pem -pubout -out public.pem
  • Both the files should be in (.pem) format. for example: private.pem file for private key and public.pem file for public key. (refer this)

Common Headers

Authorization: Bearer where is a JWT token signed using JWT issuer and secret. Content-Type: application/json in the response and in request if the API method is NOT GET

Common Request path Parameters

{version}: Defines the API Version

Common Responses

200: Successful Response. Response body varies w.r.t API 401: Unauthorized: The JWT token is missing or invalid 403: Forbidden : Not allowed to execute the concerned API 404: Entity Not Found 400: Bad Request (Error message varies w.r.t API) 201: No content: Empty Response

API Details

Visit the OpenAPI spec docs

Credits

This service is inspired by loopback4-microservice-catalog