npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sourceloop/authentication-service

v19.2.3

Published

Authentication microservice.

Downloads

1,989

Readme

@sourceloop/authentication-service

LoopBack

npm

node-current (scoped)

npm (prod) dependency version (scoped)

check-code-coverage

Overview

A 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

Maintaining the activity of the users

Whenever a user logins in to the system we make an entry in the login_activity table marking the users login time and his details. The login type can be "ACCESS","RELOGIN","LOGOUT" based on the action taken by the user. This way a track can be maintained. Api to fetch daily/monthly active users is available that gives a list of active users for the provided date range based on users selection. The actor field is configurable. The dafault value is user.id but can be changed by binding the appropriate field to AuthServiceBindings.ActorIdKey.

this.application.bind(AuthServiceBindings.ActorIdKey).to('id');

Installation


npm i @sourceloop/authentication-service

Usage

  • Create a new Loopback4 Application (If you don't have one already) lb4 testapp

  • Install the authentication service npm i @sourceloop/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 '@sourceloop/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 {
      VerifyBindings,
      AuthServiceBindings,
    } from '@sourceloop/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 '@sourceloop/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 setting its value to true and bind it to its respective key in application.ts

      import {VerifyBindings} from '@sourceloop/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. for using Google Authenticator user needs to pass client id in the payload which is optional in case for OTP

  • OAuth- using Azure AD -

    • 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.

    • 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)

    By default we are employing asymmetric token signing and verification, but if symmetric signing and verification is required it has to be explicitly provided in the manner below

    this.bind(AuthServiceBindings.Config).to({
      useSymmetricEncryption: true,
    });
  • Authenticating Password using RSA Encryption

    In order to authenticate password using RSA encrytion we need to provide private key through an env variable called PRIVATE_DECRYPTION_KEY. By employing RSA encryption and the private key through the environment variable, this approach enhances the security of password authentication, ensuring that passwords are transmitted and stored in an encrypted manner, and can only be deciphered using the designated private key.

    Its implemented through password decryption provider here which accepts password in encrypted format.It uses node-forge as default for decryption but can be overriden through this password decryption provider for using any other library.

    Note: When using .env file put your private key in single line with line breaks escaped with \n, one of the ways of doing so can be found here.

  • Using with Sequelize

    This service supports Sequelize as the underlying ORM using @loopback/sequelize extension. And in order to use it, you'll need to do following changes.

    • To use Sequelize in your application, add following to application.ts:
    this.bind(AuthServiceBindings.Config).to({
      useCustomSequence: false,
      useSequelize: true,
    });
    • Use the SequelizeDataSource in your audit datasource as the parent class. Refer this for more details.
  • Customizable Password Hashing for Enhanced Security

    For hashing and verifying of password two providers utilized are as follows:

    PasswordHashingProvider: This provider here generates a hash of a given password using bcrypt's hashing function.

    PasswordVerifyProvider: This provider here verifies whether a plain password matches a hashed password using bcrypt's comparison function

    These providers offer a flexible and modular approach to password hashing and verification within a LoopBack application. Users can easily swap out these implementations with their preferred hashing algorithms by overriding the providers, allowing for customization according to specific security requirements.

  • 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 {inject, lifeCycleObserver, LifeCycleObserver} from '@loopback/core';
import {juggler} from '@loopback/repository';
import {AuthDbSourceName} from '@sourceloop/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);
  }
}

Migrations

The migrations required for this service are processed during the installation automatically if you set the AUTH_MIGRATION or SOURCELOOP_MIGRATION env variable. The migrations use db-migrate with db-migrate-pg driver for migrations, so you will have to install these packages to use auto-migration. Please note that if you are using some pre-existing migrations or databases, they may be affected. In such a scenario, it is advised that you copy the migration files in your project root, using the AUTH_MIGRATION_COPY or SOURCELOOP_MIGRATION_COPY env variables. You can customize or cherry-pick the migrations in the copied files according to your specific requirements and then apply them to the DB.

Additionally, there is now an option to choose between SQL migration or PostgreSQL migration. NOTE : For @sourceloop/cli users, this choice can be specified during the scaffolding process by selecting the "type of datasource" option.

Database Schema

Auth DB Schema

Providers

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

ATTENTION

We would like to inform you that we have deprecated '/auth/login-token' due to security vulnerabilities. Your immediate action is required to transition away from its usage. We encourage you to transition to OAuth-compliant APIs such as '/auth/login' and '/auth/token' for secure authentication and data exchange. Refer to our documentation and reach out for support if needed. Your cooperation is appreciated in safeguarding our systems integrity.

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