@nestjs/swagger:是否可以防止网络钓鱼?

时间:2021-06-24 12:12:12

标签: node.js swagger nestjs swagger-ui nestjs-swagger

我在 Nest.js 应用程序中使用 @nestjs/swagger 来生成 Swagger 文档。

在文档中,我们有一个简单的例子,如

      const config = new DocumentBuilder()
        .setTitle('Cats example')
        .setDescription('The cats API description')
        .setVersion('1.0')
        .addTag('cats')
        .build();
      const document = SwaggerModule.createDocument(app, config);
      SwaggerModule.setup('api', app, document);

通过此实现,我遇到了安全问题,这可能会使攻击者面临网络钓鱼攻击。例如,我们有一个 swagger 页面

https://petstore.swagger.io/

攻击者可以在 URL 中添加查询参数,例如

https://petstore.swagger.io/?url=https://27.rs/card.yaml#/default/get_

这可能会导致安全问题。有什么办法可以防止吗?我们可以禁用 Swagger URL 的查询参数,或者清理它吗?转换

https://petstore.swagger.io/?url=https://27.rs/card.yaml#/default/get_ => https://petstore.swagger.io/

作为第 4 个参数的 SwaaggerModule.setup 函数可以接收选项。我试图对他们做些什么,但仍然没有结果。以下是可能的参数

export interface SwaggerCustomOptions {
  explorer?: boolean;
  swaggerOptions?: Record<string, any>;
  customCss?: string;
  customCssUrl?: string;
  customJs?: string;
  customfavIcon?: string;
  swaggerUrl?: string;
  customSiteTitle?: string;
  validatorUrl?: string;
  url?: string;
  urls?: Record<'url' | 'name', string>[];
}

我还可以在 GitHub 中看到有关此问题的未解决问题。 有提到window.history.replaceState(null, "", window.location.pathname);的用法。如何在@nestjs/swagger 中使用它?

1 个答案:

答案 0 :(得分:0)

我在@nestjs/swagger 中没有找到任何解决方案,我可以在 GitHub 中看到未解决的问题

https://github.com/swagger-api/swagger-ui/issues/4332#issuecomment-867574178

作为临时解决方案,我添加了以下部分代码来在呈现 Swagger 文档之前处理请求。

   app.use(swaggerPath, (req: Request, res: Response, next: NextFunction) => {
      // A temporary solution to prevent security issues with query params
      // Can be removed when into the swagger module will be added ability to turn off query parameters of URL
      if (Object.keys(req.query).length) {
        res.redirect(swaggerPath);
      } else {
        next();
      }
    });

其中 swaggerPath 类似于 /api/doc 或您的 swagger 路径。