首页 > 解决方案 > 有条件地放宽 CSP 策略或放宽用于显示 iframe 内容的特定 Nest 路由的 CSP - Node/NestJS

问题描述

我有带有 NestJS 作为 BFF 的 Angular 应用程序,它是一个多租户应用程序。我需要放宽 frame-src 以仅将特定 NestJS 路由的域列入白名单,并在用户不访问包含 iframe 的页面时保持策略不变。我有一个页面,其中包含链接到不同 iframe 组件的多个选项卡。我们使用了头盔来配置我们的 CSP 响应头,默认情况下不包含 frame-src 指令,并且仅在访问包含 iframe 的页面时才想要添加。iframe 设置看起来像这样,其中 config 用于在 BFF 构建 url -

<iframe width="100%" height="100%" frameBorder="0" [src]="/iframewrapper?config=config1" title="Custom Wrapper"></iframe>

BFF 控制器如下:

  loadContent(@Query() query, @Res() res) {
    this.iframeService.getUrlForFrame(query.tab).subscribe((appConfig) => {
      const html = `<!DOCTYPE html>
                    <html>
                    <body>
                      <h1>Loading content!</h1>
                      <script type="text/javascript" nonce="4AEemGb0xJptoIGFP3Nd">
                        window.addEventListener('load', () => {
                          window.location = "${appConfig.url}"
                        });
                      </script>
                    </body>
                    </html>`;
      res.send(html);
    });
  }```
To solve this issue I created a NestJS middleware which is configured only for controller that takes care of iframe related requests. Somehow below setup does not work and browser complains of CSP not in place for frame-src. 

Approach - 1
```configure(consumer: MiddlewareConsumer): void {
    consumer.apply(CSPUpdateMiddleware).forRoutes(IFrameController);
  }```

But below setup works.
Approach - 2
 ```configure(consumer: MiddlewareConsumer): void {
    consumer.apply(CSPUpdateMiddleware).forRoutes({
      path: '*',
      method: RequestMethod.ALL
    });
  }```
Can we really update the CSP policies and re-apply if needed ? Also why does the approach 2 works and not the approach 1.


标签: expressiframenestjscontent-security-policyhelmet.js

解决方案


推荐阅读