如何用Talisman移除CSP或解决Flask Swagger UI的CSP报错?
Absolutely, this is a super common pain point when pairing Talisman (which enforces a strict default Content Security Policy) with flask_swagger_ui. Swagger UI relies on external assets like Google Fonts and uses inline styles/scripts that clash with Talisman's out-of-the-box rules. Here's how to resolve this:
1. Customize Talisman's CSP Rules (Recommended)
The best approach is to adjust your CSP to explicitly allow the resources Swagger UI needs, instead of disabling CSP entirely. Here's a working example:
from flask import Flask from flask_swagger_ui import get_swaggerui_blueprint from flask_talisman import Talisman app = Flask(__name__) # Configure Swagger UI SWAGGER_URL = '/swagger' API_SPEC_URL = '/static/swagger.json' # Update this to your spec's actual path swagger_ui_bp = get_swaggerui_blueprint( SWAGGER_URL, API_SPEC_URL, config={'app_name': "Your API Name"} ) app.register_blueprint(swagger_ui_bp, url_prefix=SWAGGER_URL) # Define a CSP that accommodates Swagger UI's requirements custom_csp = { 'default-src': "'self'", 'style-src': [ "'self'", # Use the exact hashes from your error logs for better security "'sha256-uiD1ejCBF+BQY4HmKpovbP6UD3MuKGymMj+v0lhBlZs='", "'sha256-ezdv1bOGcoOD7FKudKN0Y2Mb763O6qVtM8LT2mtanIU='", "'sha256-b3IrgBVvuKx/Q3tmAi79fnf6AFClibrz/0S5x1ghdGU='", "https://fonts.googleapis.com" ], 'font-src': [ "'self'", "https://fonts.gstatic.com" # Google Fonts serves actual font files from this domain ], 'script-src': [ "'self'", "'nonce-37t0pGv0l-SZroBKCJkJlA'", # Keep your existing nonce "'sha256-VdD52vbcqq158oxfM7ms2Arg3adoR/MYPlb75qKcZPE='" # Add the script hash from your error ] } # Initialize Talisman with the custom CSP Talisman(app, content_security_policy=custom_csp) if __name__ == '__main__': app.run(debug=True)
Key Notes:
- Hashes vs 'unsafe-inline': Using the specific hashes from your error logs is far more secure than adding
'unsafe-inline', as it only allows those exact inline styles/scripts to execute. - Google Fonts Dependencies: Swagger UI pulls styles from
fonts.googleapis.comand actual font files fromfonts.gstatic.com, so both domains need to be whitelisted.
2. Can I Set CSP to "None"?
Yes, you can disable Talisman's CSP enforcement entirely, but this is strongly discouraged for production environments—it removes critical protection against XSS and other injection attacks. For development-only testing, you can do:
# Disable CSP enforcement completely Talisman(app, content_security_policy=None) # OR use an extremely permissive policy (not recommended for any public environment) Talisman(app, content_security_policy={ 'default-src': "*", 'style-src': "* 'unsafe-inline'", 'script-src': "* 'unsafe-inline' 'unsafe-eval'" })
Stick with the custom CSP approach for production to keep your app secure while supporting Swagger UI functionality.
内容的提问来源于stack exchange,提问作者Seyfullah

