- Jh123x: Blog, Code, Fun and everything in between./
- My Blog Posts and Stories/
- Reviving the Content Security Policy (CSP) on Django/
Reviving the Content Security Policy (CSP) on Django
Table of Contents
Now how do I revive the Content Security Policy (CSP) for Django?
When I was doing it in flask, there was a build in library for doing so. In that case, is there a built in one for Django as well?
I went on a journey to find out what is the Django equivalent version of building CSP for Flask. I stumbled upon this library django-csp. This library is even maintained by Mozilla, our friendly neighborhood firefox developer.
How do you install it? #
- Install it using
pip install django-csp
How do we use it? #
- Add the default directives that we want into
settings.py
- Add decorators to have special directives for special pages.
- Profit??
There are a lot of directives which are available within the documentation but I will just be going through some of the more prominent ones which I used. All the directives are assigned within the python.
An example will be a code snippet here:
CSP_DEFAULT_SRC = ("'none'",) # Sets Default-src to 'none'
Here are some of the directives which I used
CSP_STYLE_SRC
to restrict the CSS files that can be importedCSP_SCRIPT_SRC
to restrict the JavaScript files that can be importedCSP_REPORT_TO
to report CSP violationsCSP_FORM_ACTION
to restrict the form submissions
I might have mentioned it before but cspscanner is very useful when it comes to testing if the CSP policy is secure. With that, my CSP is once again mighty XD.