How to check Django security vulnerabilities and how to fix them

Use Observatory by Mozilla site to scan the security status of your site. The site also includes third-party scanners which test other security aspects of your site.

Here's an example of the scan results of a given site:

Security status grade

The best grade to get is A+ (scores can even exceed 100%), but don't be surprised a site scores a straight F (fail), even though the site has passed the basic deployment checklist.

To improve your site security, ensure you have these settings in your settings.py:

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'Strict'
SESSION_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_SSL_REDIRECT = True
X_FRAME_OPTIONS = 'DENY'
SECURE_HSTS_SECONDS = 300  # set low, but when site is ready for deployment, set to at least 15768000 (6 months)
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

Then use the SRI Hash Generator to ensure all your scripts are loaded securely from third-party sites.

Finally, the most challenging and time-consuming to implement is the Content Security Policy (CSP), particularly if the site is large, contains a lot of third-party code, and has a lot of inline scripts and styles scattered all over the project. To make the task easier, you can install Mozilla's django-csp and use your browser's console to track the security violations in your code. You will also need to fill in the following settings in your settings.py:

CSP_DEFAULT_SRC = ("'none'",)
CSP_STYLE_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'",)
CSP_FONT_SRC = ("'self'",)
CSP_IMG_SRC = ("'self'",)

This site helps to explain about CSP and what to do with inline scripts.

Optionally, you can install django-referrer-policy to set the Referrer-Policy header for added security (and higher grade!).

I am a beginner myself, and all the above are based on my research and what I did to improve my site security.


one of the security check you can perform is Deployment checklist

Run

manage.py check --deploy

other security check can be referred in official docs