OpenApi安全中的环回4自定义身份验证

时间:2020-06-22 11:45:51

标签: loopbackjs openapi loopback4

所以我使用的是自定义身份验证,但是问题是lb4没有在openApi.json或我用@authenticate装饰的路由中添加securitySchemes。

我应该手动将其添加到openapi.json中吗,如果可以,怎么办?

1 个答案:

答案 0 :(得分:1)

LoopBack 4提供了通用OAS Enhancers的概念。这些允许将OAS 3规范的新部分合并到现有规范中。

这些增强器通过asSpecEnhancer元数据绑定到应用程序。

在OpenAPI 3.0规范中,可以通过身份验证机制来保护整个API或选择性端点。


整个API规范

这表示受单个身份验证机制保护的整个API。这可能是最常见的情况。

这是通过在Security Requirement Object中添加OpenAPI Object来实现的。

身份验证组件可以为规范增强器提供新的绑定:

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),
  ];
}

真实示例

JWT身份验证扩展does the same thing,可以用作参考。


每次操作规范

这仅表示选定的端点受身份验证提供程序保护。如果API的不同部分使用不同的身份验证机制(或根本不使用),这很有用。

很遗憾,LoopBack 4 does not yet have first-class support for this yet

一种解决方法是在每个Operation Object上有选择地定义安全需求对象。

但是,这很容易出错,因为可能很难使其与实际端点保持同步。随时join the conversation对功能感兴趣。这将使维护人员可以根据社区需求更好地确定优先级。