3

我是 LoopBack v4 的新手,我正在尝试为每个请求发送一个授权密钥。我之前用过Swagger,以前是加api键的,点击右边的“Authorize”按钮后。为了避免由于我的经验不足而导致的错误,我从一个新的应用程序“Todo List”示例开始。我尝试(没有成功)遵循这篇文章的建议:Nodejs Loopback 4 add bearer token config into swagger explorer

我所做的是src/index.ts使用以下代码修改文件:

export async function main(options: ApplicationConfig = {}) {
  const spec: OpenApiSpec = {
    openapi: '3.0.0',
    info: {
      title: 'LoopBack Application v2',
      version: '1.0.2',
    },
    paths: {
    },
    securityDefinitions: [
      {
        api_key: [
          {
            type: 'apiKey',
            name: 'api_key',
            in: 'header'
          }
        ]
      },
    ],
  };

  const app = new TodoListApplication(options);
  app.api(spec);

  await app.boot();
  await app.start();

  const url = app.restServer.url;
  console.log(`Server is running at ${url}`);
  return app;
}

基本上,我添加了这一行:app.api(spec);和 config securityDefinitionsspec常数改变了and titleversion但我仍然看不到“授权”按钮。当然,我错过了什么或做错了什么。

任何帮助表示赞赏!谢谢!

4

2 回答 2

6

最后,我添加了“授权”按钮并api_key在标题中发送,使用以下配置:

  const spec: OpenApiSpec = {
    openapi: '3.0.0',
    info: {
      title: 'LoopBack Application v2',
      version: '1.0.2',
    },
    paths: {},
    security: [
      {
        api_key: ['api_key'],
      },
    ],
    components: {
        securitySchemes: {
          api_key: {
            type: 'apiKey',
            name: 'api_key',
            in: 'header'
          }
        }
    },
  };
于 2019-04-05T17:38:17.740 回答
0

在您的文件系统中创建一个安全规范文件,如下所示

import {ReferenceObject, SecuritySchemeObject} from '@loopback/openapi-v3';

export const SECURITY_SPEC = [{bearerAuth: []}];
export type SecuritySchemeObjects = {
  [securityScheme: string]: SecuritySchemeObject | ReferenceObject;
};
export const SECURITY_SCHEME_SPEC: SecuritySchemeObjects = {
  bearerAuth: {
    type: 'http',
    scheme: 'bearer',
    bearerFormat: 'JWT',
  },
};

在 super(options) 下面的 XXXX 应用程序类的 application.ts 文件中添加以下代码,并从安全规范文件中导入 SECURITY_SCHEME_SPEC、SECURITY_SPEC。

 this.api({
      openapi: '3.0.0',
      info: {title: "package or prject name", version: '1.0'},
      paths: {},
      components: {securitySchemes: SECURITY_SCHEME_SPEC},
      servers: [{url: '/'}],
      security: SECURITY_SPEC
    });

参考环回链接

于 2020-05-28T13:34:05.447 回答