Flask-Talisman 破坏了 flask-restplus 的 swagger 文档

Flask-Talisman breaks flask-restplus' swagger documentation

我最近安装了 flask-talisman,在定义了默认的内容安全策略后,我发现我的 Swagger 文档页面没有加载。

Swagger 文档页面由 flask-restplus 自动生成,它只是停止加载。

我定义的内容安全策略(CSP)是这样的:

csp = {
    'default-src': '\'self\''
}
talisman = Talisman(app, content_security_policy=csp)

这是否可以通过向 CSP 中的受信任域添加 swagger 来简单地解决,就像这样?

csp = {
    'default-src': ["'self'", "*.swagger.com"]
}
talisman = Talisman(app, content_security_policy=csp)

还是需要定义其他参数?

不是,是因为swagger-ui使用了inline scripts and styles -- here's the open issue tracker for swagger-ui and here's the open issue for flask-restplus.

flask-talisman 允许控制 'per-view' basis, so you could add the 'unsafe-inline' keyword to your CSP for that endpoint. If that's not possible with flask-restplus, you could also modify your CSP using before_request for whatever the swagger route prefix is, as outlined here

编辑:

解决方法是对允许内联脚本和样式的 Swagger 视图使用不同的 CSP:

# Swagger CSP needs to have 'unsafe-inline' in the script-src and style-src fields
SWAGGER_CSP = {
    "script-src": ["'self'", "'unsafe-inline'"],
    "style-src": ["'self'", "'unsafe-inline'"]
}

# update the CSP for the Swagger view function
app.view_functions["swagger_ui.show"].talisman_view_options = {
    "content_security_policy": SWAGGER_CSP
}