While experience in the development and production environment of django application is almost similar, however, it's entirely different from the aspect of security. These are some commonly used production deployment settings that are recommended by the official Django documentation.
Allowed hosts and debugging
This is by far the first and most important option of any Django website in produciton that must be set correctly. Open your settings.py file and do the following changes:
- Debug ModeThe first thing to do when moving your Django application from the development environment to the production is to turn your DEBUG mode False as shown below:
Debug mode should only set to TRUE in development. In production, It can cause much more damage to the security of your application. When TRUE, error messages and tracebacks will be visible to the users and it may reveal sensitive information to the public. So make sure Debug is set to False.
- Allowed HostsAllowed Hosts contains list of hosts (Domains or IP addresses) that are allowed to make requests to the application. This option specifies that your Django application should only be accessible from the hosts that are listed here.
Keep in mind that if you are using Apache or Nginx as a frontend for your Django application, then Allowed Hosts list must contain the hostnames that you provided in the server configuration file under server name and server alias.
Suppose your web server configuration file contains servername example.com, then your Allowed hosts list should look like this: ALLOWED_HOSTS = ['example.com']
Secure your secret key
It is the most crucial component of any Django application. It is a random string that is used for both encryption and decryption of CSRF tokens, cookies, and login sessions. Securing it should be the top priority.
To create a random string that will act as your secret key, use below command:openssl rand -base64 32 > /django/private_key.txt
A new file private_key.txt will be generated in /django directory. From security perspective, secret key must be loaded from a variable instead of hardcoding it in the settings. So without exposing the secret key in plane text inside settings.py file, insert below code block replacing your SECRET_KEY block:
with open('/django/private_key.txt') as f: SECRET_KEY = f.read().strip()
This method is much more safer and secure than writing the secret key in plane text inside settings.py file.
Secure session
Securing user sessions is one of the primary goal of any server administration or security expert. Wide range of cyber-attacks are performed by hijacking user sessions, which is why I'ts important to secure them.
- Secure Session CookieA session cookie sent request over an HTTPS connection. It contains login credentials and other stuff like shopping cart items. Add the following line in your settings.py file:
SESSION_COOKIE_SECURE = True
By specifying this option, a non-secure request or HTTP request comes from the user will not be presented with any cookies. Session cookies can only be transmitted over secure HTTPS connection.
- CSRF Secure CookieJust like SESSION_COOKIE_SECURE, It also uses an HTTPS connection to transmit CSRF cookies. Cookies are an important aspect of networking security. On an unsecured connection, stealing cookies is not rocket science. So we need them as secure as possible while in transit, especially CSRF cookies.
Add the following line in settings.py file:
CSRF_COOKIE_SECURE = True
Now each time a CSRF cookie will be sent, It'll be sent on HTTPS connection. An unsecured or HTTP connection request will not be served.
- Max Connection AgeWhen a request for a particular resource is made to the database, the system creates a new connection with the database to get that resource and then close the connection afterward. Connection to the database is closed instantly because the default value for CONN_MAX_AGE is 0 second.
To change the value, add the blelow line in settings.py file:
CONN_MAX_AGE = 300
By specifying the value of this attribute in seconds, the database connection will stay open for that timeframe after request completion. It can boost database performance significantly.
Secure HSTS
HSTS stands for HTTP Strict Transport Security which is a security mechanism that helps protect websites from various vulnerabilities over HTTP connection.
- SSL RedirectThis option specifies whether to redirect all HTTP connections to secure HTTPS connection. It's recommended by Django to use HTTPS for many security reasons.
To enforce SSL redirect, add the below line in settings.py file:
SECURE_SSL_REDIRECT = True
When set to True, all the unsecure HTTP traffic will be redirected to the same URL but the protocol will be HTTPS. In this way, the connection between the user and the server will be encrypted. Keep in mind that to enforce SSL redirect, your must have valid SSL Certificate from a trusted CA otherwise you might encounter an error.
- HSTS AgeIt's browser level feature that redirects HTTP traffic to HTTPS. This attribute takes value in seconds. It sets the amount of time for a client (web browser) to redirect all HTTP traffic to HTTPS in future. Add the below line in settings.py file:
SECURE_HSTS_SECONDS = 31536000
Here value 31536000 means browser will automatically redirect the future traffic from HTTP to HTTPS for the requested website.
- HSTS SubdomainsThis is another web browser level option. Add this line in settings.py file to utilize it:
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
Now that the option is set to True, HSTS policy will be applied to all the subdomains of the website. The web browser will automatically enforce HSTS on all sub-domains.
Django deployment checks
Django comes with pre-build feature of deployments checks. It will check the applicaiton configuration from security and best practices perspective and point out the settings that need your attention. You can achieve this with this simlpe command:
django-admin check --deploy
Before running this command, make sure to activate the relevant virtual environment. Output will give you all the information that you need to mitigate those vulnerabilities in the application. After correcting all the vulnerabilities, run the command again to make sure everything is safe and secure.
These are some of the commonly used settings but there is always room for more. Just keep in mind that having a valid SSL Certificate from trusted CA is necessary for most of the settings to work.