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

@nestjs/swagger: Is it possible to prevent phishing?

我在 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 page

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?

中使用

我在@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 路径。