Play 2.5.18 内容安全策略过滤器已创建但不允许加载任何 Web 元素

Play 2.5.18 Content Security Policy filter has been created but is not allowing any web elements to load

我已将我的应用程序从 2.5.12 升级到 2.5.18,但在尝试 运行 此应用程序时收到错误消息。

错误如:

Refused to load the font '<URL>' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

Refused to load the font 'http://localhost:9000/assets/css/bootstrap/glyphicons-halflings-regular.woff' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-nOIew6ekpmk+M5QFOFhJ1ur1AuDtJrbuorncKwpAfxA='), or a nonce ('nonce-...') is required to enable inline execution.

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' http://localhost:9000". Either the 'unsafe-inline' keyword, a hash ('sha256-CeNrMsFQ2CxbG0wY6+u/TJVb6zIFWXP9hv08Pgb1MmM='), or a nonce ('nonce-...') is required to enable inline execution.

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' <URL>". Either the 'unsafe-inline' keyword, a hash ('sha256-se3iZ/nePYmAviO9VXXizL4rh7Co8gaWtMzoxdwXqdk='), or a nonce ('nonce-...') is required to enable inline execution.

所以,我遵循了这个文档:

https://www.playframework.com/documentation/2.5.18/SecurityHeaders

并阅读这些帖子:

Play framework - Content Security Policy setting doesn't work?

并将我的 application.conf 更新为:

play.modules {
    enabled += "play.filters.headers.SecurityHeadersModule"
}

play.filters {
    # Security headers filter configuration
    headers {
        # The Content-Security-Policy header. If null, the header is not set.
        contentSecurityPolicy = "default-src 'self'; script-src 'self' http://localhost:9000 'unsafe-inline'; connect-src 'self'; img-src 'self' http://localhost:9000; style-src 'self' http://localhost:9000; font-src 'self' http://localhost:9000"
    }
}

但是,当我 cleancompilerun 应用程序时,我仍然收到上面列出的那些错误。好像 play.filters 没有激活。

我注意到您可以将内容安全策略添加到 html 页面本身 - 我是否需要同时执行这两项操作才能激活此过滤器?

我也知道我可以禁用这个过滤器,但听起来这不是个好主意。

我在这里发现的一件事是您需要分别为 script-srcstyle-src 以及 font-src 定义它。

所以在你的情况下:

contentSecurityPolicy = "default-src 'self'; script-src 'self' http://localhost:9000 'unsafe-inline'; connect-src 'self'; img-src 'self' http://localhost:9000; style-src 'self' http://localhost:9000 'unsafe-inline'; font-src 'self' http://localhost:9000 'unsafe-inline'"

这是针对 unsafe-inline 问题。

或者你可以把所有东西都放在 default-src 但你失去了一点安全性;).

顺便说一下,我建议将所有 inline-scripts 和 inline-styles 移动到文件中 - 这样您就可以少一个安全线程。