0
votes

So I am using a custom authentication but the problem is that lb4 doesn't add a securitySchemes in the openApi.json nor in the routes I've decorated with @authenticate.

Should I add it manually to the openapi.json, if yes, how?

1

1 Answers

1
votes

LoopBack 4 provides the concept of general OAS Enhancers. These allow merging of new slices of the OAS 3 spec into the existing spec.

These enhancers are bound to the application with asSpecEnhancer metadata.

In OpenAPI 3.0 specs, either the entire API or selective endpoints can be secured by an authentication mechanism.


Entire API spec

This denotes the entire API as secured by a single authentication mechanism. This is probably the most common scenario.

This is achieved by adding a Security Requirement Object into the OpenAPI Object.

The authentication component can provide a new binding for the spec enhancer:

import {bind} from '@loopback/core';
import {
  asSpecEnhancer,
  mergeOpenAPISpec,
  OASEnhancer,
  OpenApiSpec,
  ReferenceObject,
  SecuritySchemeObject,
} from '@loopback/openapi-v3';

export type SecuritySchemeObjects = {
  [securityScheme: string]: SecuritySchemeObject | ReferenceObject;
};

export const OPERATION_SECURITY_SPEC = [
  {
    // secure all endpoints with 'jwt'
    jwt: [],
  },
];

export const SECURITY_SCHEME_SPEC: SecuritySchemeObjects = {
  jwt: {
    type: 'http',
    scheme: 'bearer',
    bearerFormat: 'JWT',
  },
};

/**
 * A spec enhancer to add bearer token OpenAPI security entry to
 * `spec.component.securitySchemes`
 */
@bind(asSpecEnhancer)
export class SecuritySpecEnhancer implements OASEnhancer {
  name = 'bearerAuth';

  modifySpec(spec: OpenApiSpec): OpenApiSpec {
    const patchSpec = {
      components: {
        securitySchemes: SECURITY_SCHEME_SPEC,
      },
      security: OPERATION_SECURITY_SPEC,
    };
    const mergedSpec = mergeOpenAPISpec(spec, patchSpec);
    return mergedSpec;
  }
}

// A bunch of stuff was not included in this component (e.g. the constructor to register the authentication provider) for bevity.
export class JWTAuthenticationComponent implements Component {
  bindings: Binding[] = [
    createBindingFromClass(SecuritySpecEnhancer),
  ];
}

Real-world example

The JWT authentication extension does the same thing, and can be used as reference.


Per-operation spec

This would denote only select endpoint(s) as being secured by an authentication provider. This is useful if different parts of the API use different authentication mechanisms (or none at all).

Unfortunately, LoopBack 4 does not yet have first-class support for this yet.

A workaround is to selectively define the Security Requirement Object on each Operation Object.

However, this is error-prone as it may be difficult to keep it in sync with the actual endpoints. Feel free to join the conversation to show interest in the feature. This would allow the maintainers to better prioritize based on community demand.