is this very reliable ?
Yes. Setting that header within the app.after_request
decorator applies the header to all routes served by that app
.
What if I apply the CSP directly in the HTML template ( jinja2 ), is that possible?
Not something that can be done in the template itself, you'd set that header within Python as above.
Which is more reliable ?
Whilst the former method (via the app.after_request
decorator) works, it's commonly something that can be handled by the reverse proxy which your Python app server sits behind. If that's unfamiliar, have a look at the deployment docs.
For example with nginx as a reverse proxy you could put this in your server
block:
add_header Content-Security-Policy "default-src 'self';";
Or, to send the header regardless of response code:
add_header Content-Security-Policy "default-src 'self';" always;
This blog has some good advice on whether to let the reverse proxy handle sending this header, or define it in your Flask app:
Should I add a CSP header with nginx or my in application?
While it is certainly easy to add a CSP header with nginx, it also possible to add a Content-Security-Policy
header with your server side programming language ([Flask]). There are tradeoffs to doing it either way. If you have sections of your application that may require a different CSP policy then it might be easier to use your application programming language instead. Or if you plan to use features such as a CSP nonce, then it is much easier to set the Content-Security-Policy
from your application code instead of from nginx.
Also if you're deploying to a platform like Heroku, which in a basic configuration exposes the gunicorn app server directly, then it's probably eaiser to set this header in your app, unless you plan to go further and deploy an nginx buildpack.
Other cloud based load balancers may provide their own way to set these headers, independent of your app.
💡 When configuring a reverse proxy or load balacner it's worth a look at Mozilla's SSL Configuration Generator which supports nginx, AWS ALB/ELB and others. The server can then be tested with Qualys SSL test.