swagger LoopBack 4 -在API资源管理器中添加“授权”按钮

6ss1mwsb  于 2022-11-06  发布在  其他
关注(0)|答案(3)|浏览(157)

我是LoopBack v4的新手,我试着在每次请求时发送一个授权密钥。我以前用过Swagger,我习惯于在点击右边的“授权”按钮后添加api密钥。为了避免由于我缺乏经验而导致的错误,我已经开始使用一个新的应用程序“待办事项列表”的例子。我试着(没有成功)按照这篇文章的建议: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);和配置securityDefinitionsspec常量更改了titleversion,但我仍然看不到“授权”按钮。可以肯定,我遗漏了一些内容或做错了一些内容。
任何帮助都是感激不尽的!谢谢!

vaj7vani

vaj7vani1#

最后,我添加了“Authorize”按钮,并在标题中发送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'
          }
        }
    },
  };
4smxwvx5

4smxwvx52#

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

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',
  },
};

在超级(选项)下的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
    });

引用环回链路

ev7lccsx

ev7lccsx3#

对于"@loopback/core": "^4.0.3",这可以如OAS增强服务作为扩展点中所描述的那样来实现。
1.创建新的OASEnhancer类,即在my-spec.ts中创建JwtAuthSpecEnhancer

import { injectable } from '@loopback/core';
import {
  mergeOpenAPISpec,
  mergeSecuritySchemeToSpec,
  asSpecEnhancer,
  OASEnhancer,
  OpenApiSpec,
} from '@loopback/rest';

@injectable(asSpecEnhancer)
export class JwtAuthSpecEnhancer implements OASEnhancer {
  name = 'YOUR_SCHEME_NAME';

  modifySpec(spec: OpenApiSpec): OpenApiSpec {
    const securitySchemeSpec = mergeSecuritySchemeToSpec(spec, 'ANY_NAME', {
      type: 'http',
      scheme: 'bearer',
      bearerFormat: 'JWT'
    });
    const securitySpec = mergeOpenAPISpec(securitySchemeSpec, {
      security: [
        {
          ANY_NAME: [],
        },
      ]
    });
    return securitySpec;
  }
}

1.绑定到application.ts

import {ApplicationConfig, createBindingFromClass} from '@loopback/core';
import {AuthenticationComponent} from '@loopback/authentication';
import {JwtAuthSpecEnhancer} from './my-spec.ts'
export class MyRestApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {

...

this.component(AuthenticationComponent);
this.add(createBindingFromClass(JwtAuthSpecEnhancer ));

...

this.projectRoot = __dirname;
    // Customize @loopback/boot Booter Conventions here
    this.bootOptions = {
      controllers: {
        // Customize ControllerBooter Conventions here
        dirs: ['controllers'],
        extensions: ['.controller.js'],
        nested: true,
      },
    };
  }
}

搞定!
或者,对于ApiKey类型的身份验证,请参考Swagger doc。例如,可以将OAS Enhancer配置为使用header中的access_token,如下所示:

...
modifySpec(spec: OpenApiSpec): OpenApiSpec {
    const securitySchemeSpec = mergeSecuritySchemeToSpec(spec, 'token', {
      type: 'apiKey',
      name: 'access_token',
      in: 'header'
    });
    const securitySpec = mergeOpenAPISpec(securitySchemeSpec, {
      security: [
        {
          token: ['access_token'],
        },
      ]
    });
    return securitySpec;
  }
...

请注意,Loopback 4支持SecuritySchemeType = 'apiKey' | 'http' | 'oauth2' | 'openIdConnect'

相关问题