当前位置: 首页 > 知识库问答 >
问题:

在ui中无法使用Swagger承载授权

越学博
2023-03-14
    {
  "openapi": "3.0.0",
  "info": {
    "title": "LMS API Specification",
    "version": "1.0.0",
    "description": "Open documentation for LMS API"
  },
  "host": "localhost:8091",
  "basePath": "/",
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  },
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "paths": {
    "/instructor/me": {
      "get": {
        "tags": [
          "Instructor"
        ],
        "description": "Finds all classes and their status for the current user",
        "responses": {
          "200": {
            "description": "You have successfully found all classes and their status for the current user"
          }
        }
      }
    }
  },
  "tags": []
}

swagger-config.yaml

openapi: 3.0.0
info:
  title: LMS API Specification
  version: 1.0.0
  description: Open documentation for LMS API
host: localhost:8091
basePath: /
apis: ['api/v1/instructor/index.js']
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerAuth: []

app.js

import Koa from 'koa'
import cors from 'koa-cors'
import serveStatic from 'koa-static'
// import websockify from 'koa-websocket'

import Logger from './lib/Logger'
import authInit from './auth'

import index from './routes/index'
import auth from './routes/auth'
import launch from './routes/launch'
import lesson from './routes/lesson'
import v1 from './api/v1'
import Router from 'koa-router'

export default async port => {
  const koaSwagger = require('koa2-swagger-ui');
  // const app = websockify(new Koa
  const app = new Koa()
  const swaggerJSDoc = require('swagger-jsdoc');
  var router = new Router()
  await authInit(app)

  // Definitions for the swagger docs
  const swaggerDefinition = {
    info: {
      // API informations (required)
      title: 'LMS API Specification', // Title (required)
      version: '1.0.0', // Version (required)
      description: 'OpenAPI documentation for LMS', // Description (optional)
    },
    host: `localhost:8091/api/v1`, // Host (optional)
    basePath: '/', // Base path (optional)
  };
  const options = {
    // Import swaggerDefinitions
    swaggerDefinition,
    // Path to the API docs
    // Note that this path is relative to the current directory from which the Node.js is ran, not the application itself.
    apis: ['api/v1/instructor/index.js'],
  };
  // Initialize swagger-jsdoc -> returns validated swagger spec in json format
  const swaggerSpec = swaggerJSDoc(options);
  router.get('/swagger.json', async (ctx, next) => {

    ctx.set('Content-Type', 'application/json')
    ctx.body = (swaggerSpec);
    return
  });
  app.use(
    koaSwagger({
      swaggerOptions: {
        url: 'http://localhost:8091/swagger.json', // example path to json

      },
      hideTopbar: true,
      routePrefix: '/docs', // route where the view is returned
    }),
  );

  Logger.info(`Running in ${process.env.NODE_ENV} environment`)

  app
    .use(cors())
    .use(serveStatic(__dirname + '/assets'))
    .use(index.routes())
    .use(auth.routes())
    .use(launch.routes())
    .use(lesson.routes())
    .use(v1.routes())
    .use(router.routes())

  return app.listen(port, () => {
    Logger.info(`> Ready on port ${port}`)
  })
}

共有1个答案

乐正迪
2023-03-14

让它最终工作的方法是更新我的app.js文件和swagger-config.yaml文件,如下所示...

app.js

import Koa from 'koa'
import cors from 'koa-cors'
import serveStatic from 'koa-static'
// import websockify from 'koa-websocket'

import Logger from './lib/Logger'
import authInit from './auth'

import index from './routes/index'
import auth from './routes/auth'
import launch from './routes/launch'
import lesson from './routes/lesson'
import v1 from './api/v1'
import Router from 'koa-router'

export default async port => {
  const koaSwagger = require('koa2-swagger-ui');
  // const app = websockify(new Koa
  const app = new Koa()
  const swaggerJSDoc = require('swagger-jsdoc');
  var router = new Router()
  await authInit(app)

  // Definitions for the swagger docs
  const swaggerDefinition = {
    openapi: '3.0.1',
    info: {
      // API informations (required)
      title: 'LMS API Specification', // Title (required)
      version: '1.0.0', // Version (required)
      description: 'OpenAPI documentation for LMS', // Description (optional)
    },
    servers: [{url: 'http://localhost:8091/'}],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
        }
      }
    },
    security: [{
      bearerAuth: []
    }]
  };
  const options = {
    // Import swaggerDefinitions
    swaggerDefinition,
    // Path to the API docs
    // Note that this path is relative to the current directory from which the Node.js is ran, not the application itself.
    apis: ['api/v1/instructor/index.js'],
  };
  // Initialize swagger-jsdoc -> returns validated swagger spec in json format
  const swaggerSpec = swaggerJSDoc(options);
  router.get('/swagger.json', async (ctx, next) => {

    ctx.set('Content-Type', 'application/json')
    ctx.body = (swaggerSpec);
    return
  });
  app.use(
    koaSwagger({
      swaggerOptions: {
        url: 'http://localhost:8091/swagger.json', // example path to json
      },
      hideTopbar: true,
      routePrefix: '/docs', // route where the view is returned
    }),
  );

  Logger.info(`Running in ${process.env.NODE_ENV} environment`)

  app
    .use(cors())
    .use(serveStatic(__dirname + '/assets'))
    .use(index.routes())
    .use(auth.routes())
    .use(launch.routes())
    .use(lesson.routes())
    .use(v1.routes())
    .use(router.routes())

  return app.listen(port, () => {
    Logger.info(`> Ready on port ${port}`)
  })
}

swagger-config.yaml

openapi: 3.0.1
info:
  title: LMS API Specification
  version: 1.0.0
  description: Open documentation for LMS API
servers:
- url: http://localhost:8091/
apis: ['api/v1/instructor/index.js']
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - bearerAuth: []

基本上,我将OpenAPI:3.0.1添加到了Suggager定义中。

 类似资料:
  • 我的任务是在swagger-ui站点中启用授权按钮。我做了REST-Controller的留档,带有来自springdoc-openapi-ui-依赖项的@操作或@Api响应等注释。现在我应该在昂首阔步的表面启用授权按钮。 我有以下介绍:https://www.baeldung.com/spring-boot-swagger-jwt但在这里我必须包括springfox到我的maven依赖,但当我这

  • 我试图使用Swagger动态地记录我的SpringBoot应用程序的REST API。 霸气配置: 谢谢你的帮助!

  • iam无法在运行应用程序时检索到swagger ui,http://localhost:8080/Swagger-ui.html,有人能说出原因吗?

  • 嗨,我正在使用springboot 1.5.3。大摇大摆地释放。当我运行应用程序时,我可以通过访问“localhost:3030/v2/api文档”来访问json swagger响应。但我无法访问“localhost:3030/swagger ui.html”,同时显示未找到“/swagger ui.html”的映射。我如何解决这个问题。 依赖关系 招摇过市配置

  • 但是最近我们转移到了3.0的新版本。结果,这个javascript不再工作了。 是否有任何方法可以使用Swagger UI 3.0中的任何javascript添加Bearer auth的头,而不是单击“授权”按钮。 我这样问是因为每当我打开swagger UI调用API时,手动添加auth真的很烦人。

  • 我正在使用swagger,swagger用户界面与Spring rest api来获得一个平台来测试/记录API,所以我需要在swagger用户界面中获得oAuth2授权,我在授权服务器上使用密码授权,所以我不得不使用包