Logic logo
  1. 21

Top Django settings for secure deployments

By pariskasid on 21 Jan 2025

Although we are not a cybersecurity company, we take many steps towards securing the web applications we are building again attacks. There are a few of them that are such low hanging fruits for deploying more secure Python web applications, that it would be a shame if we did not take care of every time. Below are four Django settings we make sure to configure appropriately before deploying every new web app for the first time.

First, is the SECRET_KEY. It needs to be a huge randomly generated string. It is used for many security utilities, one of which is cryptographically signing the session cookies of the users. Its value should NEVER be checked out in Git, so a good option for reading the value is sourcing it from the environment with os.getenv, or even better using sec, our open source library with sec.load that can read both from the environment, but from secret files in /run/secrets too. For local development, you return a default value in the previous functions like, development_use_only.

Talking about cookies, the combination of SESSION_COOKIE_SECURE (set to True), CSRF_COOKIE_SECURE (set to True) will further guard the security of your cookies. These two settings will ensure that both the users’ session and CSRF protection cookies will be transmitted only over HTTPS and will not be accessible from JavaScript.

Therefore, HTTPS should be enforced with SECURE_PROXY_SSL_HEADER (set to ("HTTP_X_FORWARDED_PROTO", "https") ) along with SECURE_SSL_REDIRECT (set to True). The combination of these two settings will ensure that all URLs build by Django in production use the https protocol, while also understanding that the reverse proxy is using HTTPS and finally redirect HTTP requests to HTTPS.

Finally, setting SECURE_HSTS_SECONDS will safeguard the HTTPS communication of the Django web application from the browser side as well. It should be set to a non-zero number to hint the browsers to only send HTTPS requests to the Django web application.

Securing a web application is a critical task that is far from completed ever, let alone from a few Django settings. The provided settings above though will definitely protect a Django web application from a set of common attacks that otherwise would be low hanging fruits for an attacker to compromise it.

Stay tuned with LOGIC

Get notified when an article lands on the LOGIC blog.