1.8.1 • Published 2 years ago

@microloop/authentication-service v1.8.1

Weekly downloads
-
License
-
Repository
github
Last release
2 years ago

authentication-service

LoopBack

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 @bleco/authentication and @bleco/authorization. For reference, below is the flow for the login code generation that uses to authenticate client, authenticate user and authorization decorators from these npm packages -

Login Flow

Installation

npm i @microloop/authentication-service

Usage

  • Create a new Loopback4 Application (If you don't have one already) lb4 testapp
  • Install the authentication service npm i @microloop/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 '@microloop/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.
  • Start the application npm start

Environment Variables

NameRequiredDefault ValueDescription
NODE_ENVYNode environment value, i.e. dev, test, prod
LOG_LEVELYLog level value, i.e. error, warn, info, verbose, debug
DB_HOSTYHostname for the database server.
DB_PORTYPort for the database server.
DB_USERYUser for the database.
DB_PASSWORDYPassword for the database user.
DB_DATABASEYDatabase to connect to on the database server.
DB_SCHEMAYDatabase schema used for the data source. In PostgreSQL, this will be public unless a schema is made explicitly for the service.
REDIS_HOSTYHostname of the Redis server.
REDIS_PORTYPort to connect to the Redis server over.
REDIS_URLYFully composed URL for Redis connection. Used instead of other settings if set.
REDIS_PASSWORDYPassword for Redis if authentication is enabled.
REDIS_DATABASEYDatabase within Redis to connect to.
JWT_SECRETYSymmetric signing key of the JWT token.
JWT_ISSUERYIssuer of the JWT token.
USER_TEMP_PASSWORDNTemporary password that can be used during development.
GOOGLE_AUTH_URLNGoogle OAuth2.0 authorization URL if authentication strategy is set to Google
GOOGLE_AUTH_CLIENT_IDNGoogle client ID for the service
GOOGLE_AUTH_CLIENT_SECRETNGoogle client secret for the service
GOOGLE_AUTH_TOKEN_URLNGoogle OAuth2.0 authorization URL if authentication strategy is set to Google
GOOGLE_AUTH_CALLBACK_URLNGoogle callback URL for the client configuration in Google
FORGOT_PASSWORD_LINK_EXPIRYN1800Expiration period of temporary password in seconds. 1800 seconds (30 minutes) is the default.
KEYCLOAK_HOSTNHostname of the Keycloak instance
KEYCLOAK_REALMNRealm (tenant) in Keycloak
KEYCLOAK_CLIENT_IDNKeycloak client ID for the service
KEYCLOAK_CLIENT_SECRETNKeycloak client secret for the service
KEYCLOAK_CALLBACK_URLNKeycloak callback URL for the client configuration in Google
HTTPS_PROXYNHttps proxy url for keycloak auth

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 '@microloop/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 BLECO_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 database, they may be effected. In such scenario, it is advised that you copy the migration files in your project root, using the AUTH_MIGRATION_COPY or BLECO_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.

Database Schema

Auth DB Schema

Providers

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

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